Reputation: 23
I'm trying to remove all markers from map on button click;
gmarkers = []; //define empty array for all markers
Add markers, show map:
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
}
}
Remove markers:
removeMarkers(){
if (this.gmarkers) {
for (let i in this.gmarkers) {
this.gmarkers[i].setMap(null);
}
this.gmarkers = [];
}
}
Also try with this approach to remove:
removeMarkers(){
for(var i=0; i<this.gmarkers.length; i++){
this.gmarkers[i].setMap(null);
}
this.gmarkers = [];
}
I got error:
this.gmarkers[i].setMap is not a function
Upvotes: 1
Views: 5305
Reputation: 29785
Try this : Use foreach
instead
removeMarkers(){
this.gmarkers.foreach((marker)=>{
marker.setMap(null);
marker = null;
})
this.gmarkers = [];
}
And In your addMarkersToMap()
method, you are pushing the marker
variable, instead you need to push myMarker
inside gmarkers
I guess.
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
}
}
Upvotes: 3