javascript - 谷歌地图 : Return is Not working in Reverse Geocoading

标签 javascript google-maps-api-3 return return-value anonymous-function

我正在尝试 ReverseGeCoding 它的工作,但我无法获得返回值

function reverseGeoCode(lat,lng) {
 var reverseGeoAddress = '';
 var geocoder = new google.maps.Geocoder();
 var latlng = new google.maps.LatLng(lat, lng);
 geocoder.geocode({'latLng': latlng}, function(results, status) {
     if (status == google.maps.GeocoderStatus.OK) {
         if (results[1]) {
             if(results[1].formatted_address.length){
                 reverseGeoAddress = results[1].formatted_address;
                 //NOTE: when i console.log(reverseGeoAddress );
                 //its working fine i am getting the address
                 return reverseGeoAddress;
                   //but return not working.

             }  
         }
      } 
  });
}

当我像这样调用我的函数时

   var address = reverseGeoCode(31.518945,74.349316);

现在每次我的地址变量都是“未定义”时; 为什么会这样? 有什么提示吗?

最佳答案

函数reverseGeoCode没有任何返回值

return reverseGeoAddress; is inside anonymous function.

简单的修复是 - 您可以使用回调,因为它是异步函数。 “callback”可以是您调用位置的处理程序。

// Invoking reverseGeoCode....
reverseGeoCode(lat,lng, function(myAddress){ 
  // Your custom code goes here...
});

function reverseGeoCode(lat,lng, callback) {
var reverseGeoAddress = '';
 var geocoder = new google.maps.Geocoder();
 var latlng = new google.maps.LatLng(lat, lng);
 geocoder.geocode({'latLng': latlng}, function(results, status) {
     if (status == google.maps.GeocoderStatus.OK) {
         if (results[1]) {
             if(results[1].formatted_address.length){
                 reverseGeoAddress = results[1].formatted_address;
                 // Callback the handler if it exists here
                 // No return value
                 callback(reverseGeoAddress);
             }  
         }
      } 
  });
}

关于javascript - 谷歌地图 : Return is Not working in Reverse Geocoading,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/12420577/

相关文章:

javascript - 使用javascript在谷歌地图中绘制多边形

javascript - 如何在 Google map 监听器中使用 bool?

python - 在 Python 上返回 None

java - 在带有finally block 的方法中放置return 语句

javascript - 使用 Google Maps Javascript API 从一组预定义位置获取最近的位置

javascript - Google map V3 自定义叠加层子级停止接收鼠标事件

javascript - 如何设置 webstorm 以自动将分号添加到 javascript 函数、方法等

javascript - 如何停止执行其余代码 - javascript

javascript - 从 Angular Controller 打开 Bootstrap 弹出窗口

javascript - block 在 Masonry 中与 jQuery 不对齐