Google 地图地理编码器

Google map Geocoder

我使用 google geocoder 获取 latlng,当 initMap 被调用时,我得到两个警报,第一个值是 undefined ,然后获取 lat 值,获取 undefined 值有什么问题,如何解决?我需要立即获取值。

function initMap(){
      var addr = '1600 Amphitheatre Parkway, Mountain View, CA';
      var code = getLatLng(addr);
      alert(code.lat); // --> alert_1
}

function getLatLng(addr) {
    var geocoder = new google.maps.Geocoder();
     geocoder.geocode({'address': addr }, function (results, status) {
       var lat,lng = 0;
         if (status == google.maps.GeocoderStatus.OK) {
              lat = results[0].geometry.location.lat();
              lng = results[0].geometry.location.lng();
         }
         alert(lat); // --> alert_2
         return {lat : lat,lng : lng};
     });
 }

函数geocode是一个异步函数。因此,您在 initMap 函数的警报中获得 code.latundefined 以及 getLatLng 函数中的地理编码值。您可以在 getLatLng 函数的参数中添加一个回调函数来解决您的问题,如下所示:

function initMap() {
  var addr = '1600 Amphitheatre Parkway, Mountain View, CA';
  getLatLng(addr, function(code) {
    alert(code.lat);
  });
}

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