gpt4 book ai didi

javascript - 检索全局变量

转载 作者:行者123 更新时间:2023-12-02 16:44:42 25 4
gpt4 key购买 nike

如何检索 city值进入location对象?

var city = "";
var state = "";
geocoder = new google.maps.Geocoder();
var latlng = new google.maps.LatLng(position.coords.latitude, position.coords.longitude);
geocoder.geocode({
'latLng': latlng
}, function(results, status) {
if (status == google.maps.GeocoderStatus.OK) {
//Check result 0
var result = results[0];
//look for locality tag and administrative_area_level_1
for (var i = 0, len = result.address_components.length; i < len; i++) {
var ac = result.address_components[i];
if (ac.types.indexOf("locality") >= 0) city = ac.long_name;
if (ac.types.indexOf("administrative_area_level_1") >= 0) state = ac.long_name;
}
}
});

var location = {lat: position.coords.latitude, lng: position.coords.longitude, city: city};

最佳答案

geocoder.geocode的调用是异步的。在异步代码返回之前,代码执行到达 var location 的声明;因此城市尚未定义。

提前声明位置,然后添加到回调函数中的位置对象

var location = {lat: position.coords.latitude, lng: position.coords.longitude};
geocoder = new google.maps.Geocoder();
var latlng = new google.maps.LatLng(position.coords.latitude, position.coords.longitude);
geocoder.geocode({
'latLng': latlng
}, function(results, status) {
if (status == google.maps.GeocoderStatus.OK) {
//Check result 0
var result = results[0];
//look for locality tag and administrative_area_level_1
for (var i = 0, len = result.address_components.length; i < len; i++) {
var ac = result.address_components[i];
if (ac.types.indexOf("locality") >= 0) location.city = ac.long_name;
if (ac.types.indexOf("administrative_area_level_1") >= 0) location.state = ac.long_name;
}
}
});

关于javascript - 检索全局变量,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/27211010/

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