gpt4 book ai didi

javascript - 如何从Geocoder中提取 map 中心坐标?

转载 作者:行者123 更新时间:2023-12-02 17:53:41 27 4
gpt4 key购买 nike

var address = "Boston";
var geocoder = new google.maps.Geocoder();
geocoder.geocode( { 'address': address}, function(results, status) {
if (status == google.maps.GeocoderStatus.OK) {
map.setCenter(results[0].geometry.location);
map.fitBounds(results[0].geometry.bounds);
createLatLng();
} else {
alert("Geocode was not successful for the following reason: " + status);
}

});

function createLatLng() {
var MapCenter=map.getCenter();
var x=MapCenter.lat(), y=MapCenter.lng(), z=0;
}

现在我有这个代码,大部分取自谷歌的这个例子:https://developers.google.com/maps/documentation/javascript/geocoding

现在 x 和 y 变量未定义。这是为什么?如何正确获取 x 和 y 变量?

这里还有演示(如果有帮助的话):http://jsbin.com/ilOTIQIn/1/edit

最佳答案

由于 geocode 是异步的,您将无法在您想要的位置设置 MapCenter,因为 API 调用的结果不会返回在那时候。我建议您使用回调来帮助您管理通话:

var MapCenter, map, x, y, z;

function geocode(callback) {
geocoder.geocode( { 'address': address}, function(results, status) {
if (status == google.maps.GeocoderStatus.OK) {
map.setCenter(results[0].geometry.location);
map.fitBounds(results[0].geometry.bounds);
callback();
} else {
alert("Geocode was not successful for the following reason: " + status);
}
});
}

geocode(function () {
MapCenter = map.getCenter();
x = MapCenter.lat(), y = MapCenter.lng(), z = 0;
});

关于javascript - 如何从Geocoder中提取 map 中心坐标?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/21145041/

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