gpt4 book ai didi

javascript - Google Maps JavaScript API v3 删除标记

转载 作者:塔克拉玛干 更新时间:2023-11-02 22:05:14 25 4
gpt4 key购买 nike

我已经查看了大量“类似”问题,但似乎没有一个解决方案/答案对我有用,所以我们开始吧:我正在生成一个带有单个标记“onload”的简单 Google map ,然后我有一个菜单列表有点像这样

<ul>
<li class="toggle" id="beaches">Item</li>
<li class="toggle" id="towns">Item</li>
<ul>

点击时使用这些数组标记填充 map

jQuery-

$(".toggle").click(function(){
setMarkers(map,$(this).attr('id'));
});

var beaches = [
['Beach 1',38.285827, 20.611038, 4],
['Beach 2', 38.304958,20.604515, 5],
['Beach 3',38.301691,20.597649, 3]
];

var towns = [
['Town 1',38.343003, 20.535679, 4],
['Town 2',38.339334,20.545807, 5]
];

我的人口函数如下所示:

function setMarkers(map, locations) {
for (var i = 0; i < locations.length; i++) {
var newmarker = locations[i];
var myLatLng = new google.maps.LatLng(newmarker[1], newmarker[2]);
var marker = new google.maps.Marker({
position: myLatLng,
map: map,
title: newmarker[0],
zIndex: newmarker[3]
});
}

但我需要/想要做的是在添加新标记之前先清除所有 标记。请建议谢谢

最佳答案

您需要存储标记,并为要从 map 中删除的每个标记调用 setMap(null)

你可以尝试这样的事情:

var setMarkers = (function() {
var oldMarkers = null;
return function(map, locations){
//Clearing markers, if they exist
if(oldMarkers && oldMarkers.length !== 0){
for(var i = 0; i < oldMarkers.length; ++i){
oldMarkers[i].setMap(null);
}
}
//Adding new markers
oldMarkers = [];
for (var i = 0; i < locations.length; i++) {
var newmarker = locations[i];
var myLatLng = new google.maps.LatLng(newmarker[1], newmarker[2]);
var marker = new google.maps.Marker({
position: myLatLng,
map: map,
title: newmarker[0],
zIndex: newmarker[3]
});
oldMarkers.push( marker );
}
};
})();

关于javascript - Google Maps JavaScript API v3 删除标记,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/10631206/

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