2013-12-14 90 views
0

我在我的地图控制器中有一个函数将地址转换为google.maps.latlng,我想返回这个值,但是我的函数没有返回任何东西。我认为这是因为值在另一个函数内部发生了变化,但我无法弄清楚如何解决这个问题。控制器的帮助函数不返回任何东西

addressToLatLng: function(address) { 
    var geocoder = new google.maps.Geocoder(), lat, lng, latlng; 
    geocoder.geocode({ 'address': address }, function(results, status) { 
     if (status == google.maps.GeocoderStatus.OK) { 
      lat = results[0].geometry.location.lat(); 
      lng = results[0].geometry.location.lng(); 
      latlng = new google.maps.LatLng(lat, lng); 
      console.log(latlng); // will give me the object in the log 
     } 
    }); 
    return latlng; // nothing happens 
}, 

回答

0

这是因为geocode调用是异步的,所以你想存在之前,该函数返回值。

您可以使用回调调用者获得的价值,当它到达:

addressToLatLng: function(address, callback) { 
    var geocoder = new google.maps.Geocoder(), lat, lng, latlng; 
    geocoder.geocode({ 'address': address }, function(results, status) { 
     if (status == google.maps.GeocoderStatus.OK) { 
      lat = results[0].geometry.location.lat(); 
      lng = results[0].geometry.location.lng(); 
      latlng = new google.maps.LatLng(lat, lng); 
      callback(latlng); 
     } 
    }); 
}, 

用法:

yourController.addressToLatLng(address, function(latlng){ 
    console.log(latlng); 
}); 
+0

Firstofall的感谢!代码工作正常,但不解决我的问题。我想在回调之外使用latlng。例如。 A1 = this.addressToLatLng(地址1)// A1得到经纬度 A2 = this.addressToLatLng(地址2) google.maps.geometry.spherical.computeDistanceBetween(A1,A2) – user3102211

+0

@ user3102211的值/对象:为了做到这一点你需要一个时间机器,这样你就可以走向未来,并在它存在之前获得价值。这是回调被称为价值是第一次为您提供,在此之前,你无法得到它。您可以从方法中返回一个承诺,但这只是将回调放入可以返回的对象中的一种方法,您仍然需要异步获取承诺的值。 – Guffa

+0

那么有没有其他的可能性来获得从你当前的位置到列表的某些地址的距离(没有lat/lng,因为当它们已经给出时它很容易)? – user3102211

相关问题