Javascript 如何在信息窗口中显示点击标记和地址上获得latlng
我的谷歌地图API中有几个标记Javascript 如何在信息窗口中显示点击标记和地址上获得latlng,javascript,google-maps,google-maps-api-3,Javascript,Google Maps,Google Maps Api 3,我的谷歌地图API中有几个标记 marker = new google.maps.Marker({ position: pos, map: map }); var infoWindow = new google.maps.InfoWindow(); google.maps.event.addListener(mark
marker = new google.maps.Marker({
position: pos,
map: map
});
var infoWindow = new google.maps.InfoWindow();
google.maps.event.addListener(marker, 'click', (function(marker, i) {
return function() {
infoWindow.setContent(setInfoWindow({this.position}));
infoWindow.open(map, marker);
}
})(marker, i));
在这里,当我点击标记时,我显示了infowindow,同时,我在infowindow上分配了地址,该地址从latlng转换为address
这是setInfoWindow()
这里,它显示的是未定义的
我的程序对吗
我的简单想法是
当我点击marker时,我必须从marker中获取latlng并转换为address,并且必须显示在infowindow中,您在其中调用setInfoWindow,您正在传递一个结构,其位置周围带有
{}
符号:
setInfoWindow({this.position})
但是,在函数本身中,当您直接引用它时,您将其视为一个简单变量,如下所示:
function setInfoWindow(pos){
然后
geocoder.geocode({'latLng': pos}
只需将位置本身传递给函数:
setInfoWindow(this.position)
这是因为异步而发出的。方法
google.maps.event.addListener(marker, 'click', (function(marker, i) {
return function() {
setInfoWindow(this.position);
infoWindow.open(map, marker);
}
})(marker, i));
function setInfoWindow(pos){
var geocoder = new google.maps.Geocoder();
geocoder.geocode({'latLng': pos}, function(results, status) {
if (status == google.maps.GeocoderStatus.OK) {
infoWindow.setContent(results[0].formatted_address);
} else {
alert('Geocoder failed due to: ' + status);
}
});
}
当我点击marker时,我调用了一个方法,在这个方法中,我显示了infowindow哪一行/变量是“未定义的”?重复的
google.maps.event.addListener(marker, 'click', (function(marker, i) {
return function() {
setInfoWindow(this.position);
infoWindow.open(map, marker);
}
})(marker, i));
function setInfoWindow(pos){
var geocoder = new google.maps.Geocoder();
geocoder.geocode({'latLng': pos}, function(results, status) {
if (status == google.maps.GeocoderStatus.OK) {
infoWindow.setContent(results[0].formatted_address);
} else {
alert('Geocoder failed due to: ' + status);
}
});
}