我创建了一个在Google地图上绘制多个KML图层的for循环。之后,我试图在每个KML折线上添加一个infoWindow。我可以为每一行显示infowindow,但它们都具有相同的内容:我绘制的最后一个KML文件的URL。
以下是代码:
function initmap(urls){
// Creating an option object for the map
var myLatlng = new google.maps.LatLng(61.130298, 24.009358);
var options = {
zoom: 7,
center: myLatlng,
mapTypeId: google.maps.MapTypeId.ROADMAP
};
// Initializing the map
var map = new google.maps.Map(document.getElementById('map_canvas'), options);
if(urls != null) {
var ctaLayer = new Array();
var url = new Array();
for(var i=0;i<urls.length;i++) {
url[i] = urls[i];
url[i] = url[i]+"?dummy="+(new Date()).getTime();
ctaLayer[i] = new google.maps.KmlLayer(url[i], {suppressInfoWindows: true});
ctaLayer[i].setMap(map);
// Creating an InfoWindow object
var infowindow = new google.maps.InfoWindow({content: url[i]});
google.maps.event.addListener(ctaLayer[i], 'click', function(kmlEvent) {
var clickPos = kmlEvent.latLng;
var posX = new google.maps.LatLng(clickPos.lat(), clickPos.lng());
infowindow.close();
infowindow.setPosition(posX);
infowindow.open(map);
});
}
}
}
我做错了什么?
如果我这样做,(将infowindows添加到数组中),当我点击KML时,InfoWindows甚至不会出现。
var infowindow = new Array();
infowindow[i] = new google.maps.InfoWindow({
content: urls[i]
});
google.maps.event.addListener(ctaLayer[i], 'click', function(kmlEvent) {
var clickPos = kmlEvent.latLng;
var posX = new google.maps.LatLng(clickPos.lat(), clickPos.lng());
infowindow[i].close();
infowindow[i].setPosition(posX);
infowindow[i].open(map);
});
答案 0 :(得分:0)
我假设你只想要一次出现一个infoWindow。 (您的点击事件有infoWindow.close())您需要从此行中删除content:选项。
var infowindow = new google.maps.InfoWindow({content: url[i]});
然后将其添加到addListener函数中:
var infoWindow = new google.map.InfoWindow();
....
google.maps.event.addListener(ctaLayer[i], 'click', function(kmlEvent) {
var clickPos = kmlEvent.latLng;
var posX = new google.maps.LatLng(clickPos.lat(), clickPos.lng());
infowindow.close();
infowindow.setPosition(posX);
infoWindow.setContent(url[i]);
infowindow.open(map);
});
更好的是,将infoWindow创建为全局,供所有eventHandler使用。