我呼叫API并在几秒间隔后绘制新标记。新标记被绘制,但旧标记仍然存在。我想在绘制新标记时清除旧标记。这是我的代码。
var myMarkers = [];
var i;
var marker = new google.maps.Marker({
position: new google.maps.LatLng(12.967086,77.746564),
map: map,
});
setInterval(function(){
$.post(contextPath+"/api/getlocations", {} , function(data){
var response = data;
var locations = response.locations;
var marker, i;
for (var i = myMarkers.length; i > 0; i--) {
myMarkers[i].setMap(null);
}
myMarkers = [];
for (i = 0; i < locations.length; i++) {
marker = new google.maps.Marker({
position: new google.maps.LatLng(locations[i][1], locations[i][2]),
map: map
});
google.maps.event.addListener(marker, 'click', (function(marker, i) {
return function() {
infowindow.open(map, marker);
}
})(marker, i));
myMarkers.push(marker);
}
});
}, 5000);
*地图已初始化。
任何帮助将不胜感激。感谢
答案 0 :(得分:1)
在窗口级别声明myMarkers以管理标记集合
var myMarkers = [];
在创建标记之前清除上一个
for (i = 0; i < myMarkers.length; i++) {
myMarkers.[i].setMap(null);
}
myMarkers = [];
...
marker = new google.maps.Marker({
position: new google.maps.LatLng(locations[i][1], locations[i][2]),
map: map
});
//在标记集合中添加标记
myMarkers.push(marker);