我正在尝试在单击按钮时从地图中删除所有标记;
gmarkers = []; //define empty array for all markers
添加标记,显示地图:
addMarkersToMap(markers) {
for(let marker of markers) {
var position = new google.maps.LatLng(marker.latitude, marker.longitude);
var myMarker = new google.maps.Marker({
position: position,
title: marker.name
});
myMarker(this.map);
this.gmarkers.push(marker); //push all markers to gmarkers array
}
}
删除标记:
removeMarkers(){
if (this.gmarkers) {
for (let i in this.gmarkers) {
this.gmarkers[i].setMap(null);
}
this.gmarkers = [];
}
}
还可以尝试使用此方法删除:
removeMarkers(){
for(var i=0; i<this.gmarkers.length; i++){
this.gmarkers[i].setMap(null);
}
this.gmarkers = [];
}
我收到错误:
this.gmarkers[i].setMap 不是一个函数
试试这个:改用foreach
removeMarkers(){
this.gmarkers.foreach((marker)=>{
marker.setMap(null);
marker = null;
})
this.gmarkers = [];
}
在你的addMarkersToMap()
方法中,你正在推动marker
变量,相反,你需要myMarker
推入gmarkers
我猜。
addMarkersToMap(markers) {
for(let marker of markers) {
var position = new google.maps.LatLng(marker.latitude, marker.longitude);
var myMarker = new google.maps.Marker({
position: position,
title: marker.name
});
myMarker(this.map);
//replace marker with myMarker
this.gmarkers.push(myMarker); //push all markers to gmarkers array
}
}