【问题标题】:Setting a variable in function parameter [duplicate]在函数参数中设置变量[重复]
【发布时间】:2017-02-06 23:49:02
【问题描述】:

我有以下功能。

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

我知道我在这里遗漏了一些基本的东西。但是 alert 语句中的 retvalue 总是空白的。如何在调用geocode的功能块中设置。

亲切的问候

迈克尔

【问题讨论】:

  • retvalue仅在geocoder.geocode({latLng: pos}, function (results, status) {的回调中可用

标签: javascript google-maps


【解决方案1】:

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

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

【讨论】:

  • 非常感谢。我修改了代码,以便将 MapMarker 传递给函数 reversegeocode 并使用地理编码结果设置标记的标题。
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2015-10-25
相关资源
最近更新 更多