Google maps API地理编码问题
问题描述:
我想我只是在做一些愚蠢的事情,因为我的JavaScript技能并不是最棒的。下面的代码会产生一个空白的,灰色地图:Google maps API地理编码问题
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'));
}
然而,如果简单地改变 “中心: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);
现在的工作,谢谢! – XanderNGCC 2013-03-25 02:41:59