如何从 Google Maps JavaScript 地理编码器返回经度和纬度? [英] How do I return a longitude and latitude from Google Maps JavaScript geocoder?

查看:24
本文介绍了如何从 Google Maps JavaScript 地理编码器返回经度和纬度?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

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

HTML

<div id="map_canvas" style="width: 320px; height: 480px;"></div><div><input id="address" type="textbox" value="悉尼,新南威尔士州"><input type="button" value="Encode" onclick="display()">

JavaScript

var 地理编码器;无功地图;函数初始化(){地理编码器 = 新的 google.maps.Geocoder();var latlng = new google.maps.LatLng(-34.397, 150.644);var myOptions = {变焦:8,中心:latlng,mapTypeId: google.maps.MapTypeId.ROADMAP}map = new google.maps.Map(document.getElementById("map_canvas"), myOptions);}函数代码地址(){var address = document.getElementById("address").value;var loc=[];geocoder.geocode({'地址':地址},函数(结果,状态){如果(状态 == google.maps.GeocoderStatus.OK){loc[0]=results[0].geometry.location.lat();loc[1]=results[0].geometry.location.lng();} 别的 {alert("地理编码失败,原因如下:" + status);}});返回位置;}功能显示(){var long_lat=codeAddress();警报(long_lat);}

解决方案

因为你的函数codeAddress被执行了,给loc分配了空数组,向google geocoder执行异步请求,返回loc为空,因为它的实际值是在来自 google 的响应来时分配的.换句话说,警报应该在响应处理程序中:

var 地理编码器;无功地图;函数初始化(){地理编码器 = 新的 google.maps.Geocoder();var latlng = new google.maps.LatLng(-34.397, 150.644);var myOptions = {变焦:8,中心:latlng,mapTypeId: google.maps.MapTypeId.ROADMAP}map = new google.maps.Map(document.getElementById("map_canvas"), myOptions);}函数代码地址(){var address = document.getElementById("address").value;var loc=[];//下一行创建异步请求geocoder.geocode({'地址':地址},函数(结果,状态){//这是处理响应的函数如果(状态 == google.maps.GeocoderStatus.OK){loc[0]=results[0].geometry.location.lat();loc[1]=results[0].geometry.location.lng();警报(位置);//loc 包含地理编码坐标的地方} 别的 {alert("地理编码失败,原因如下:" + status);}});//毫无意义,因为它总是 []//此行在创建 AJAX 请求后立即执行,但不在响应到来后执行返回位置;}功能显示(){代码地址();}

这就是 AJAX 的工作原理...过程会产生回调处理程序.


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

 函数 codeAddress() {var address = document.getElementById("address").value;geocoder.geocode({'地址':地址},函数(结果,状态){如果(状态 == google.maps.GeocoderStatus.OK){var loc=[];//现在不需要在外部函数中定义它loc[0]=results[0].geometry.location.lat();loc[1]=results[0].geometry.location.lng();显示(位置);} 别的 {alert("地理编码失败,原因如下:" + status);}});}功能显示(long_lat){警报(long_lat);}

html:


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

函数代码地址(回调){...geocoder.geocode({'地址':地址},函数(结果,状态){...回调( loc );//而不是显示( loc );...}...}代码地址(显示);//执行地理编码

When I use the code below its alerting a blank value? why is that?

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);
  }

解决方案

because your function codeAddress is executed, assigning empty array to loc, executing asynchronous request to google geocoder and returns loc, which is empty, because its real value is assigned when response from google comes. In other words, allert should be inside response handler:

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();
  }

this is how AJAX works... process results in callback handlers.


if you want to separate geocoding and 'dispalying' you can execute display function inside handler:

  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()">


you can make it even more generic, if you will geocode not only to display. Then you can define callback as parameter to codeAddress function:

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

codeAddress( display ); // to execute geocoding

这篇关于如何从 Google Maps JavaScript 地理编码器返回经度和纬度?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆