jac*_*dev 7 javascript jquery google-maps google-maps-api-3
我目前正在开展的一个项目需要实施带有多个标记和多个信息框的谷歌地图.引用地图API这似乎是一个很好的起点:
https://developers.google.com/maps/documentation/javascript/examples/icon-complex
所以我使用这个代码作为基础,并从那里建立.现在,我坚持使用的是为每个标记添加一个独特的信息框.这是我的来源
http://jsfiddle.net/jackthedev/asK5v/1/
你可以看到我试图调用第一个元素,其中选择了数组中的任何对象,它完全适用于lat,long和title,而不是contentstring变量.
for (var i = 0; i < locations.length; i++) {
var office = locations[i];
var myLatLng = new google.maps.LatLng(office[1], office[2]); //works here
var infowindow = new google.maps.InfoWindow({content: contentString});
var contentString =
'<div id="content">'+
'<div id="siteNotice">'+
'</div>'+
'<h1 id="firstHeading" class="firstHeading">'+ office[0] + '</h1>'+ //doesnt work here
'<div id="bodyContent">'+
'</div>'+
'</div>';
var infowindow = new google.maps.InfoWindow({content: contentString});
var marker = new google.maps.Marker({
position: myLatLng,
map: map,
icon: globalPin,
title: office[0], //works here
});
google.maps.event.addListener(marker, 'click', function() {
infowindow.setContent(contentString);
infowindow.open(map,this);
});
}
Run Code Online (Sandbox Code Playgroud)
要查看我想解释的内容,只需单击上面演示中的每个标记,您将看到一个标题为"中国"的信息框弹出窗口.由于某种原因,它抓住每个标记的最后一个对象的第一个元素.
我想要实现的是,如果有意义的话,所有信息框都是唯一的标记?因此,当我点击新加坡的标记时,信息框将使用我之前定义的数组对象弹出新加坡的标题.
谢谢,我希望我已经足够清楚了
问题是变量infoWindow会在循环的每次迭代中被覆盖.通常这不是问题,除了内部的部分addListener是异步回调,并且每次调用时,引用infoWindow都不再正确.
你可以通过创建一个闭包来解决这个问题infoWindow,这样每个回调函数都有自己的副本.用这个:
google.maps.event.addListener(marker, 'click', getInfoCallback(map, contentString));
Run Code Online (Sandbox Code Playgroud)
使用随附的辅助函数:
function getInfoCallback(map, content) {
var infowindow = new google.maps.InfoWindow({content: content});
return function() {
infowindow.setContent(content);
infowindow.open(map, this);
};
}
Run Code Online (Sandbox Code Playgroud)
| 归档时间: |
|
| 查看次数: |
5385 次 |
| 最近记录: |