gpt4 book ai didi

javascript - 单击同一标记两次将打开两个信息窗口

转载 作者:行者123 更新时间:2023-12-02 13:51:56 24 4
gpt4 key购买 nike

我让信息窗口正常工作,但由于某种原因,如果我多次单击同一标记,它会打开多个相同的信息窗口。我有一种感觉,它一定与我的代码有关,但我不能完全确定它是什么。如有任何帮助,我们将不胜感激。

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();
});

最佳答案

如果您不希望每次单击标记时都创建一个信息窗口,则不要每次单击标记时都创建一个新窗口,而是为标记创建一个(或者为 map 创建一个,如果您只想要打开一个),然后在点击监听器中打开它。

function addMarker(feature) {
var marker = new google.maps.Marker({
position: feature.position,
map: map,
type: feature.type,
description: feature.description
});
// create infowindow for the marker
var infoWindow = new google.maps.InfoWindow({});
marker.addListener('click', function() {
map.setCenter(marker.getPosition());
// set the content of the infowindow
infoWindow.setContent(marker.description);
// open the infowindow on the marker.
infoWindow.open(map,marker);
});
markers.push(marker);
}

proof of concept fiddle

关于javascript - 单击同一标记两次将打开两个信息窗口,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/40961246/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com