2

我需要从 Postcode 中获取 Lat/Lng,所以我使用的是 Google Map/Geocode API。

我无法从 Geocode 脚本中运行的函数中获取 lat/lng 变量。我正在使用的代码如下:

<input id="address" type="textbox" value="">
<script type="text/javascript">
var lat;
var lng;
function addressurls(address) {
var address = document.getElementById("address").value;
var geocoder = new google.maps.Geocoder();
geocoder.geocode({'address': address}, function postcodesearch(results, status) 
{   
  if (status == google.maps.GeocoderStatus.OK) 
  {
    var lat = results[0].geometry.location.lat();
    var lng = results[0].geometry.location.lng();
  }
  else {
    alert("Error");
  }
  return lat;
  return lng;
});
var laturl = "&lat=";
var lonurl = "&lon=";
var postcode = document.getElementById("address").value;
var addressurl = "/distributors-search?address=" + postcode + laturl + lat+ lonurl + lng;
parent.location=addressurl;
}
</script>
<input type="button" value="Encode" onclick="addressurls('address'), parent.location=addressurl">

有谁知道如何修理它?

4

1 回答 1

3

地理编码是异步的,需要在回调函数中使用返回的数据

<input id="address" type="textbox" value="">
<script type="text/javascript">
var lat;
var lng;
function addressurls(address) {
var address = document.getElementById("address").value;
var geocoder = new google.maps.Geocoder();
geocoder.geocode({'address': address}, function postcodesearch(results, status) 
{   
  if (status == google.maps.GeocoderStatus.OK) 
  {
    var lat = results[0].geometry.location.lat();
    var lng = results[0].geometry.location.lng();
    var laturl = "&lat=";
    var lonurl = "&lon=";
    var postcode = document.getElementById("address").value;
    var addressurl = "/distributors-search?address=" + postcode + laturl + lat+ lonurl + lng;
    parent.location=addressurl;
  }
  else {
    alert("Error");
  }
});

}
</script>
<input type="button" value="Encode" onclick="addressurls('address'), parent.location=addressurl">
于 2013-04-01T21:59:09.507 回答