![](/img/trans.png)
[英]Rounding the place.geometry.location value in Google Maps API
[英]Google Maps API - results.geometry.location[0] returning null
对javascript而言还相当陌生,并尝试制作一个简单的地图应用程序。 我正在尝试将新地图围绕通过函数传递的地址居中。 我遇到的问题是,我总是不知道它总是返回null,是否必须以函数格式指定返回类型?
我的代码:
<script>
var geocoder;
var map;
function initialize() {
var address = document.getElementById('address').value;
var latlng = GetLatLong(address);
alert(latlng);
var mapOptions = {
zoom: 8,
center: latlng
}
var map = new google.maps.Map(document.getElementById('map-canvas'), mapOptions);
}
function GetLatLong(address) {
var geocoder = new google.maps.Geocoder();
geocoder.geocode( { 'address': address}, function(results, status) {
if (status == google.maps.GeocoderStatus.OK) {
alert(results[0].geometry.location)
return results[0].geometry.location;
} else {
alert('Geocode was not successful for the following reason: ' + status);
}
});
}
google.maps.event.addDomListener(window, 'load', initialize);
</script>
我的地址文本有一个div,地图位置有一个div。 为了进行调试,我将alert(“”)放在某些位置以查看在运行时调用它的顺序,为什么在调用函数之前先调用我放置第一个警报的行?
谢谢
您正在执行的Google Maps API调用是异步的。 用外行的术语来说,这意味着一旦您开始调用,程序的其余部分将保持独立于其执行。 它实际上在程序的其余部分运行。 传递给地址解析器调用的函数的目的是处理该调用异步返回的数据。
您需要更改代码以执行以下操作:
function initialize() {
var address = document.getElementById('address').value;
GetLatLong(address);
}
var map;
function GetLatLong(address) {
var geocoder = new google.maps.Geocoder();
geocoder.geocode( { 'address': address}, function(results, status) {
if (status == google.maps.GeocoderStatus.OK) {
alert(results[0].geometry.location)
var latlng = results[0].geometry.location;
var mapOptions = {
zoom: 8,
center: latlng
};
map = new google.maps.Map(document.getElementById('map-canvas'), mapOptions);
} else {
alert('Geocode was not successful for the following reason: ' + status);
}
});
}
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.