[英]Google maps API issue with geocoder
我認為我只是在做一些愚蠢的事情,因為我的JavaScript技能不是最出色的。 以下代碼生成空白的灰色地圖:
function initialize() {
directionsDisplay = new google.maps.DirectionsRenderer();
geocoder = new google.maps.Geocoder();
var address = "Minneapolis, MN";
geocoder.geocode( { 'address': address}, function(results, status) {
if (status == google.maps.GeocoderStatus.OK)
{
lat = results[0].geometry.location.lat();
lng = results[0].geometry.location.lng();
addresslatlng = new google.maps.LatLng(results[0].geometry.location.lat(),results[0].geometry.location.lng());
}
else
{
alert(status);
}
});
var mapOptions = {
zoom: 7,
mapTypeId: google.maps.MapTypeId.ROADMAP,
center: addresslatlng
};
var map = new google.maps.Map(document.getElementById('map-canvas'),
mapOptions);
directionsDisplay.setMap(map);
directionsDisplay.setPanel(document.getElementById('directions-panel'));
}
但是,如果僅將“ center:addresslatlng”更改為:
center: new google.maps.LatLng(-34.397, 150.644)
工作正常。
我嘗試使用lat和lng ,但也不起作用:
center: new google.maps.LatLng(lat, lng)
有任何想法嗎?
地理編碼是異步的。 您需要在回調函數中使用結果:
function initialize() {
directionsDisplay = new google.maps.DirectionsRenderer();
geocoder = new google.maps.Geocoder();
var address = "Minneapolis, MN";
geocoder.geocode( { 'address': address}, function(results, status) {
if (status == google.maps.GeocoderStatus.OK)
{
lat = results[0].geometry.location.lat();
lng = results[0].geometry.location.lng();
addresslatlng = new google.maps.LatLng(results[0].geometry.location.lat(),results[0].geometry.location.lng());
var mapOptions = {
zoom: 7,
mapTypeId: google.maps.MapTypeId.ROADMAP,
center: addresslatlng
};
var map = new google.maps.Map(document.getElementById('map_canvas'),
mapOptions);
directionsDisplay.setMap(map);
directionsDisplay.setPanel(document.getElementById('directions-panel'));
}
else
{
alert(status);
}
});
}
我認為這
lat = results[0].geometry.location.lat();
lng = results[0].geometry.location.lng();
真的應該更像這樣
lat = results[0].geometry.location.lat;
lng = results[0].geometry.location.lng;
同樣,您創建lat
和lon
,然后不要在下一行中使用它們。 改變這個
addresslatlng = new google.maps.LatLng(results[0].geometry.location.lat(),results[0].geometry.location.lng());
對此
addresslatlng = new google.maps.LatLng(lat, lng);
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.