Javascript 谷歌地图v3反向地理编码
使用Google Map v3反向地理编码samplesource使此源Javascript 谷歌地图v3反向地理编码,javascript,google-maps,google-maps-api-3,Javascript,Google Maps,Google Maps Api 3,使用Google Map v3反向地理编码samplesource使此源 var map; var geocoder; var marker; function initialize() { geocoder = new google.maps.Geocoder(); var mapOptions = { zoom : 14, cente
var map;
var geocoder;
var marker;
function initialize() {
geocoder = new google.maps.Geocoder();
var mapOptions = {
zoom : 14,
center : new google.maps.LatLng(30, 30)
};
map = new google.maps.Map(document.getElementById('map-canvas'),
mapOptions);
}
function codeLatLng() {
var latlng = new google.maps.LatLng(30, 30);
alert("call codeLatLng() 1");
geocoder.geocode({'latLng': latlng}, function(results, status) {
alert("call codeLatLng() 2");
if (status == google.maps.GeocoderStatus.OK) {
if (results[1]) {
map.setZoom(11);
marker = new google.maps.Marker({
position: latlng,
map: map
});
infowindow.setContent(results[1].formatted_address);
infowindow.open(map, marker);
} else {
alert('No results found');
}
} else {
alert('Geocoder failed due to: ' + status);
}
});
}
google.maps.event.addDomListener(window, 'load', initialize);
codeLatLng();
我调用函数codeLatLng();代码的最后一行
因此,调用函数codeLatLng()并发出警报消息“callcodelatlng()1
但是不调用“call codeLatLng()2”,代码也不工作
我的代码有什么问题
我的代码有什么问题
在初始化map和geocoder变量之前,您正在执行codeLatLng(当DOM完成加载时初始化运行,codeLatLng立即运行)
这样做会更好:
var map;
var geocoder;
var marker;
function initialize() {
geocoder = new google.maps.Geocoder();
var mapOptions = {
zoom : 14,
center : new google.maps.LatLng(30, 30)
};
map = new google.maps.Map(document.getElementById('map-canvas'),
mapOptions);
// map and geocoder initialized
codeLatLng();
}
function codeLatLng() {
var latlng = new google.maps.LatLng(30, 30);
alert("call codeLatLng() 1");
geocoder.geocode({'latLng': latlng}, function(results, status) {
alert("call codeLatLng() 2");
if (status == google.maps.GeocoderStatus.OK) {
if (results[1]) {
map.setZoom(11);
marker = new google.maps.Marker({
position: latlng,
map: map
});
infowindow.setContent(results[1].formatted_address);
infowindow.open(map, marker);
} else {
alert('No results found');
}
} else {
alert('Geocoder failed due to: ' + status);
}
});
}
google.maps.event.addDomListener(window, 'load', initialize);
错误控制台中有任何消息吗?没有控制台是干净的没有错误我会尝试从数据处理函数中取出一些代码,只留下警报。此外,我会在数据处理函数之后放置另一个警报,但仍然在codeLatLng()函数中。谢谢,我认为geocoder的首字母是google.maps.event.addDomListener(窗口'load',initialize);地理编码器在onload函数中进行初始化。但在原始代码中运行codeLatLng后,直到页面加载后,才会运行该功能。