【发布时间】:2016-12-04 17:11:24
【问题描述】:
我让 infowindows 工作,但由于某种原因,如果我多次点击相同的标记,它会打开多个相同的 infowindow。我有一种感觉,它必须与我的代码有关,但我不能完全确定它是什么。任何帮助表示赞赏。
var map;
var markers = [];
function initMap() {
map = new google.maps.Map(document.getElementById('map_canvas'), {
zoom: 14,
center: new google.maps.LatLng(33.6894120, -117.9872660),
mapTypeId: 'roadmap',
disableDefaultUI: true
});
function addMarker(feature) {
var marker = new google.maps.Marker({
position: feature.position,
icon: icons[feature.type].icon,
map: map,
type: feature.type,
title: feature.title,
description: feature.description
});
marker.addListener('click', function() {
map.setCenter(marker.getPosition());
var infoWindow = new google.maps.InfoWindow({
map: map,
pixelOffset: new google.maps.Size(0, -60)
});
infoWindow.setContent(marker.description);
infoWindow.setPosition(marker.position);
google.maps.event.addListener(map, 'drag', function() {
infoWindow.close();
});
google.maps.event.addListener(map, 'click', function() {
infoWindow.close();
});
});
markers.push(marker);
}
filterMarkers = function(getType) {
//console.log(getType);
for (var i = 0; i < markers.length; i++) {
if (markers[i].type == getType || getType == "") {
markers[i].setVisible(true);
} else {
markers[i].setVisible(false);
}
}
}
var features = [
{
position: new google.maps.LatLng(-33.91721, 151.22630),
type: 'type1',
description: 'Description1'
},{
position: new google.maps.LatLng(-33.91721, 151.22630),
type: 'type2',
description: 'Description2'
},{
position: new google.maps.LatLng(-33.91721, 151.22630),
type: 'type3',
description: 'Description3'
}
];
for (var i = 0, feature; feature = features[i]; i++) {
addMarker(feature);
}
}
$(document).ready(function(){
initMap();
});
【问题讨论】:
-
你能提供更多你的代码吗?您在哪里创建标记变量?
-
我添加了 for 循环,您还需要什么吗?
-
我的意思是您正在推送到标记数组,但我看不到您定义它的位置,这可能是您遇到此错误的原因。
-
Mert,我已经添加了我的完整代码。您是否看到任何可能是错误代码的内容?
-
你能在initMap函数中定义map和markers变量然后再试一次吗?
标签: javascript google-maps google-maps-api-3 google-maps-markers