JavaScript函数没有返回谷歌地图lat / long的值

时间:2015-04-09 06:20:15

标签: javascript google-maps google-maps-api-3 latitude-longitude

我使用此功能从谷歌地图获取纬度/经度

function getLatLong(address){
  var geo = new google.maps.Geocoder;

  geo.geocode({'address':address},function(results, status){
    if (status == google.maps.GeocoderStatus.OK) {
      return (results[0].geometry.location.k + ',' + results[0].geometry.location.D);
    } else {
      return;
    }

  });
}

它实现了我想做的事情,但是当我在另一个函数中使用它时:getLatLong('new york, times square'),我得到了undefined作为回报。如果我设置console.log(results[0].geometry.location.k + ',' + results[0].geometry.location.D);而不是return,我会在控制台中获取该位置(如果我调用该函数,例如,document.ready)。

为什么这样,我应该如何正确使用它?

2 个答案:

答案 0 :(得分:1)

这里的笑话是geoCode没有返回任何内容,但它希望你直接处理函数回调内部的地图。您可以将它放在console.log中并执行任何操作,但不能返回并处理该函数。

查看示例https://developers.google.com/maps/documentation/javascript/examples/geocoding-simple,您将看到这是真的。

修改

仍然存在一些解决方法,请查看以下代码:

 var geocoder; 

  function initialize() { 
      geocoder = new google.maps.Geocoder(); 
      var latlng = new google.maps.LatLng(40.730885,-73.997383); 
      codeLatLng(function(addr){ 
          alert(addr); 
       }); 
   } 

    function codeLatLng(callback) { 
         var latlng = new google.maps.LatLng(40.730885,-73.997383); 
         if (geocoder) { 
             geocoder.geocode({'latLng': latlng}, function(results, status) { 
                  if (status == google.maps.GeocoderStatus.OK) { 
                      if (results[1]) { 
                        callback(results[1].formatted_address); 
                       } else { 
                          alert("No results found"); 
                        } 
                   } else { 
                       alert("Geocoder failed due to: " + status); 
                   } 
               }); 
          } 
     }

上面的代码片段说明了如何使用显式回调。

来源: How do I return a variable from Google Maps JavaScript geocoder callback?

<强> EDIT2:

您的代码已相应修改:

  function getLatLong(address, callback){ 
      var geo = new google.maps.Geocoder; 
      geo.geocode({'address':address,   function(results, status){ 
           if (status == google.maps.GeocoderStatus.OK) { 
                 callback (results[0].geometry.location.k + ',' + results[0].geometry.location.D); 
            } else { 
                 // do sth with error. 
            } 
        }); 
   }

并称之为:

 getLatLong(address, function(addr){ 
          // do whatever with addr attribute
          alert(addr); 
       }); 

也许这有助于你了解一下。

答案 1 :(得分:0)

您正在呼叫getLantLong('new york, times square');

而不是getLatLong('new york, times square');

检查拼写