如何在使用谷歌地理编码将地址转换为坐标后使用console.log数据?

时间:2016-04-17 12:33:26

标签: javascript google-maps

我正在开发一个应用程序,我需要从地理编码文本地址派生的console.log地理坐标。我在javascript中编写了以下代码:

var geocoder = new google.maps.Geocoder();

   function address_to_coordinates(address_text) {
    var address = address_text;
    geocoder.geocode( { 'address': address}, function(results, status) {
      if (status == google.maps.GeocoderStatus.OK) {
        return results[0].geometry.location;

      } else {
        alert("Geocode was not successful for the following reason: " + status);
      }
    });
  }

  console.log(address_to_coordinates('London'));

出于某种原因,它打印出未定义的'在控制台。有没有人看到它的原因?

1 个答案:

答案 0 :(得分:0)

您需要使用回调

var geocoder = new google.maps.Geocoder();

   function address_to_coordinates(address_text, callback) {
    var address = address_text;
    geocoder.geocode( { 'address': address}, function(results, status) {
      if (status == google.maps.GeocoderStatus.OK) {
        callback(results[0].geometry.location);

      } else {
        alert("Geocode was not successful for the following reason: " + status);
      }
    });
  }

address_to_coordinates('London', function(location){
  console.log(location);
});