javascript - 如何从 Google Maps JavaScript 地理编码器返回经度和纬度?

标签 javascript google-maps geocoding

<分区>

当我使用下面的代码时,它会提示空白值吗?这是为什么?

HTML

<body onload="initialize()">
 <div id="map_canvas" style="width: 320px; height: 480px;"></div>
  <div>
    <input id="address" type="textbox" value="Sydney, NSW">
    <input type="button" value="Encode" onclick="display()">
  </div>
</body>

JavaScript

var geocoder;
var map;


  function initialize() {
    geocoder = new google.maps.Geocoder();
    var latlng = new google.maps.LatLng(-34.397, 150.644);
    var myOptions = {
      zoom: 8,
      center: latlng,
      mapTypeId: google.maps.MapTypeId.ROADMAP
    }
    map = new google.maps.Map(document.getElementById("map_canvas"), myOptions);
  }

  function codeAddress() {
    var address = document.getElementById("address").value;
    var loc=[];

    geocoder.geocode( { 'address': address}, function(results, status) {
      if (status == google.maps.GeocoderStatus.OK) {
        loc[0]=results[0].geometry.location.lat();
        loc[1]=results[0].geometry.location.lng();

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

    return loc;
  }

  function display(){
     var long_lat=codeAddress();
    alert(long_lat);
  }

最佳答案

因为您的函数 codeAddress 被执行,将空数组分配给 loc,对 google geocoder 执行异步请求并返回 loc,它是空的,因为它的真实值是在 google 响应到来时分配的。换句话说,allert 应该在响应处理程序中:

var geocoder;
var map;


  function initialize() {
    geocoder = new google.maps.Geocoder();
    var latlng = new google.maps.LatLng(-34.397, 150.644);
    var myOptions = {
      zoom: 8,
      center: latlng,
      mapTypeId: google.maps.MapTypeId.ROADMAP
    }
    map = new google.maps.Map(document.getElementById("map_canvas"), myOptions);
  }

  function codeAddress() {
    var address = document.getElementById("address").value;
    var loc=[];

    // next line creates asynchronous request
    geocoder.geocode( { 'address': address}, function(results, status) {
      // and this is function which processes response
      if (status == google.maps.GeocoderStatus.OK) {
        loc[0]=results[0].geometry.location.lat();
        loc[1]=results[0].geometry.location.lng();

        alert( loc ); // the place where loc contains geocoded coordinates

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

    // pretty meaningless, because it always will be []
    // this line is executed right after creating AJAX request, but not after its response comes
    return loc;
  }

  function display(){
     codeAddress();
  }

这就是 AJAX 的工作原理...处理结果产生回调处理程序。


如果你想分离地理编码和“显示”,你可以在处理程序中执行显示功能:

  function codeAddress() {
    var address = document.getElementById("address").value;

    geocoder.geocode( { 'address': address}, function(results, status) {
      if (status == google.maps.GeocoderStatus.OK) {
        var loc=[]; // no need to define it in outer function now
        loc[0]=results[0].geometry.location.lat();
        loc[1]=results[0].geometry.location.lng();

        display( loc ); 

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

  }

  function display( long_lat ){
     alert(long_lat);
  }

html:

<input type="button" value="Encode" onclick="codeAddress()">


如果您不仅要对显示进行地理编码,还可以使其更加通用。然后你可以将回调定义为 codeAddress 函数的参数:

function codeAddress( callback ) {
...
 geocoder.geocode( { 'address': address}, function(results, status) {
   ...
   callback( loc ); // instead of dispaly( loc );
   ...
 }
...
}

codeAddress( display ); // to execute geocoding

关于javascript - 如何从 Google Maps JavaScript 地理编码器返回经度和纬度?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/5245915/

相关文章:

php - 我的广播电台网站的 JSON 代码?

javascript函数从字符串中剥离和解析转义序列,以便对转义字符串进行着色

google-maps - 如果重新加载 Google Map API v3 偏离中心(不是通常的 'resize' 东西)

android - android honeycomb 中的弹出/覆盖屏幕

gps - 在带有校准点的 map 上将经度和纬度转换为X Y

linux - 如何使用 CURL 命令使用 web 服务?

尝试对对象调用 get 时,Javascript 不会抛出错误

javascript - Javascript 中的 For 循环与 while 循环

ios - 如何保存 GMSCameraPosition?

google-maps - 适用于跟踪的 map API