2017-02-06 204 views
-1

我有以下功能。在函数参数中设置变量

function geocodePosition(pos, inputField) { 
    var retvalue = ""; 
    geocoder = new google.maps.Geocoder(); 
    geocoder.geocode({latLng: pos}, function (results, status) { 

      if (status == google.maps.GeocoderStatus.OK) { 
       retvalue = results[0].formatted_address; 
       inputField.value = retvalue; 
      } else { 
      alert('Cannot determine address at this location status [' + status + "]"); 
      } 

    }); 
    alert ("retvalue : " + retvalue); 
    return retvalue; 
} 

我知道我错过了一些基本的东西。但警报声明中的retvalue总是空白。我如何在调用地理编码的功能块中设置它。

亲切的问候

迈克尔

+0

的'retvalue'仅适用于'geocoder.geocode({经纬度:POS}回调,功能(结果,状态){' –

回答

0

这是因为地理编码过程是异步。这意味着您的警报在数据存在之前执行。你可以使用这样的回调函数:

reverseGeocoder: function (lat, lng, callback) { 

    var geocoder = new google.maps.Geocoder; 
    var addressComponents = {}; 
    geocoder.geocode({ 
     'location': { 
      lat:lat, 
      lng: lng 
     } 
    }, function (results, status){ 
     if(status === google.maps.GeocoderStatus.OK){ 

       callback(results); 
      } else { 
       alert('No information found.'); 
      } 

     }else { 
      alert("Error "+status); 
     } 
    }); 

用法:

doGeocode (lat, lng, function (response){ 
//here are your data 
)}; 
+0

非常感谢,我修改了代码以便将MapMarker传递给函数reversegeocode,并使用地理编码结果设置标记的标题。 – mbieren