[英]Why does Google Maps Geocoder not call initialize?
我正在嘗試讓Google Maps Geocoder從地址返回LatLng,然后使用位於中心的LatLng初始化地圖。
我已經看到了有關此主題的一些問題,並提出了一些建議,即應首先使用任意中心初始化地圖,然后再重新設置地圖,但這似乎很浪費。
在將全局緯度和經度更改為零之前,以下代碼可以正常工作。 然后用地址調用geocder並返回LatLng。 我得到的只是一個空白窗口,並且不會觸發初始化函數中的警報。
在我進行以0,0初始化然后居中的路線之前,有人可以解釋為什么它不起作用嗎?
謝謝
var lat = 37.425593;
var lon = -122.075915;
var address = '1600 Amphitheatre Pky, Mountain View, CA';
var LatLon = new google.maps.LatLng(0, 0);
function initialize() {
alert("2. "+LatLon);
var mapOptions = {
center: LatLon,
zoom: 14,
mapTypeId: google.maps.MapTypeId.ROADMAP
};
var map = new google.maps.Map(document.getElementById('map-canvas'), mapOptions);
var marker = new google.maps.Marker({
position: LatLon,
map: map
});
}
if (lat == 0 && lon == 0) {
alert('address = '+address);
var geocoder = new google.maps.Geocoder();
geocoder.geocode({'address': address}, function(results, status) {
if (status == google.maps.GeocoderStatus.OK) {
if (results[0]) {
LatLon = results[0].geometry.location;
alert("1. "+LatLon);
google.maps.event.addDomListener(window, 'load', initialize);
} else {
alert("No results found");
}
} else {
alert("Geocoder failed: " + status);
}
});
} else {
alert('lat/lon = '+lat+' '+lon);
LatLon = new google.maps.LatLng(lat, lon);
alert("1. "+LatLon);
google.maps.event.addDomListener(window, 'load', initialize);
}
地理編碼器是異步的。 您尚未將代碼放在上下文中,但是返回坐標所花費的時間必須表示,當坐標從服務器返回時,窗口加載事件已經觸發,因此initialize函數永遠不會運行。 如果您使用onload事件啟動地址解析操作,或者直接調用initialize並將代碼放在頁面底部,則該方法將起作用,直到頁面完全呈現(並且地圖具有)。
<script type="text/javascript">
var address = '1600 Amphitheatre Pky, Mountain View, CA';
var LatLon = new google.maps.LatLng(0, 0);
function initialize(LatLon) {
var mapOptions = {
center: LatLon,
zoom: 14,
mapTypeId: google.maps.MapTypeId.ROADMAP
};
var map = new google.maps.Map(document.getElementById('map-canvas'), mapOptions);
var marker = new google.maps.Marker({
position: LatLon,
map: map
});
}
var geocoder = new google.maps.Geocoder();
geocoder.geocode({'address': address}, function(results, status) {
if (status == google.maps.GeocoderStatus.OK) {
if (results[0]) {
var LatLon = results[0].geometry.location;
initialize(LatLon);
} else {
alert("No results found");
}
} else {
alert("Geocoder failed: " + status);
}
});
</script>
</body>
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.