如何从Google Map API函数中获取javascript lat / lng变量
作者:互联网
我需要从邮政编码中获取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">
有谁知道如何修理它?
解决方法:
地理编码是异步的,您需要在回调函数中使用返回的数据
<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">
标签:javascript,google-maps-api-3,google-geocoder 来源: https://codeday.me/bug/20191007/1865976.html