在函数参数中设置变量

时间:2017-02-06 15:45:30

标签: javascript google-maps

我有以下功能。

 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;
 }

我知道我在这里缺少一些基本的东西。但警报声明中的重估值总是空白。如何在地理编码调用的功能块中设置它。

亲切的问候

迈克尔

1 个答案:

答案 0 :(得分: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
)};