![](/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.