How to get a javascript lat/lng variable out of a Google Map API function

情到浓时终转凉″ 提交于 2019-12-09 01:31:39

问题


I need to get the Lat/Lng from a Postcode, so I'm using Google Map/Geocode API.

I can't get the lat/lng variable out of the function running within the Geocode script. The code I'm using is below:

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

Does anyone know how to fix it?


回答1:


Geocoding is asynchronous, you need to use the returned data in the callback function

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


来源:https://stackoverflow.com/questions/15752345/how-to-get-a-javascript-lat-lng-variable-out-of-a-google-map-api-function

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!