[英]Google Maps API - results.geometry.location[0] returning null
fairly new to javascript and trying to make a simple map application. 对javascript而言还相当陌生,并尝试制作一个简单的地图应用程序。 I am trying to center a new map around an address that is passed through a function. 我正在尝试将新地图围绕通过函数传递的地址居中。 The issue I have is it is always being returned null which I do not understand, do I have to specify return types in the function format? 我遇到的问题是,我总是不知道它总是返回null,是否必须以函数格式指定返回类型?
My code: 我的代码:
<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>
I have a div for the address text and a div for the map location. 我的地址文本有一个div,地图位置有一个div。 To debug I put alert("") in some places to see the order in which it gets called on runtime, why would the line I put the first alert be called before the function is called? 为了进行调试,我将alert(“”)放在某些位置以查看在运行时调用它的顺序,为什么在调用函数之前先调用我放置第一个警报的行?
Thanks 谢谢
The Google Maps API call that you are performing is asynchronous. 您正在执行的Google Maps API调用是异步的。 In layman's terms that means that as soon as you start the call, the rest of your program keeps executing independent of it. 用外行的术语来说,这意味着一旦您开始调用,程序的其余部分将保持独立于其执行。 It is essentially running to the side of the rest of your program. 它实际上在程序的其余部分运行。 The purpose of the function that you pass to the geocoder call is to deal with the data that the call returns asynchronously. 传递给地址解析器调用的函数的目的是处理该调用异步返回的数据。
You would need to change your code to do something like this: 您需要更改代码以执行以下操作:
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.