作者热门文章
- html - 出于某种原因,IE8 对我的 Sass 文件中继承的 html5 CSS 不友好?
- JMeter 在响应断言中使用 span 标签的问题
- html - 在 :hover and :active? 上具有不同效果的 CSS 动画
- html - 相对于居中的 html 内容固定的 CSS 重复背景?
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/
我是一名优秀的程序员,十分优秀!