Hey everyone! I’m trying to figure out how to remove all the markers from my map using Google Maps API v3. In the old version (v2), it was super easy. You just had to use map.clearOverlays() and boom, all markers were gone.
But now I’m stuck with v3 and can’t find a similar method. I’ve been digging through the docs but no luck so far. It’s driving me crazy!
Does anyone know how to do this in v3? Maybe there’s a new function or a different approach? I’d really appreciate any help or tips you can give me. Thanks in advance!
Here’s a quick example of what I’m working with:
function initMap() {
const myMap = new google.maps.Map(document.getElementById('map'), {
center: {lat: 40.7128, lng: -74.0060},
zoom: 12
});
const marker1 = new google.maps.Marker({
position: {lat: 40.7484, lng: -73.9857},
map: myMap
});
const marker2 = new google.maps.Marker({
position: {lat: 40.7829, lng: -73.9654},
map: myMap
});
// How do I remove all these markers at once?
}
I’ve been in your shoes, Isaac! When I first migrated from v2 to v3, I was also scratching my head about this. Here’s what I’ve found works well:
Instead of using map.clearOverlays(), you need to keep track of your markers in an array. Then, you can loop through this array to remove all markers at once. Here’s how I do it:
let markers = [];
function addMarker(location) {
const marker = new google.maps.Marker({
position: location,
map: myMap
});
markers.push(marker);
}
function clearMarkers() {
for (let i = 0; i < markers.length; i++) {
markers[i].setMap(null);
}
markers = [];
}
Now, whenever you add a marker, use addMarker(). When you want to clear all markers, just call clearMarkers(). This approach has worked like a charm for me in several projects.
Hope this helps! Let me know if you need any clarification.
hey isaac, same problem here! i use an array to track markers and then loop thru to setMap(null). try: let markers = ; function deleteAll() { markers.forEach(m=>m.setMap(null)); markers = ; } hope it works!
I’ve encountered this issue before, and there’s a straightforward solution. In Google Maps API v3, you need to manage your markers manually. Here’s an efficient approach:
Create an array to store your markers:
let markersArray = [];
When adding markers, push them to this array:
const marker = new google.maps.Marker({
position: position,
map: myMap
});
markersArray.push(marker);
To clear all markers, iterate through the array:
function clearMarkers() {
for (let i = 0; i < markersArray.length; i++) {
markersArray[i].setMap(null);
}
markersArray = [];
}
Call clearMarkers() whenever you need to remove all markers. This method has proven reliable in my projects. It’s a bit more code than v2, but it offers greater flexibility in marker management.