gpt4 book ai didi

javascript - 如何从 Google Map API 函数中获取 javascript lat/lng 变量

转载 作者:行者123 更新时间:2023-11-29 22:14:57 25 4
gpt4 key购买 nike

我需要从邮政编码获取纬度/经度,所以我使用的是 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 Map API 函数中获取 javascript lat/lng 变量,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/15752345/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com