Lauren Lauren - 1 month ago 9
Javascript Question

Google Map: Remove all Circles

I'm looking for a javascript function that will clear all drawings from my map; something like

map.removeMarkers()
or
map.removeOverlays()
, but for shapes - specifically circles.

I've seen some answers about how to do this on Android, but I'm looking for a web solution. I'm using gmaps.js to draw my circles:

// create circle loop
for( i = 0; i < data.mapArray.length; i++ ) {

circle = map.drawCircle({
lat: data.mapArray[i].lat,
lng: data.mapArray[i].lng,
radius: parseInt(data.mapArray[i].radius),
strokeColor: '#'+data.mapArray[i].color,
strokeWeight: 8,
fillOpacity: 0,

click: (function (e) {
return function () {
$('#'+modalType).modal({
remote: modalURL+e
});
};
})(data.mapArray[i].id)
});

} // end loop


I'm guessing that within this loop I need to add the circles to an array, and then call a function to clear all of them, but I'm not sure how to execute that.

Answer

One easy solution is to store the objects in an array

<input type="button" value="Clear all" onclick="removeAllcircles()"/>
<script>
var circles = [];
// create circle loop
for( i = 0; i < data.mapArray.length; i++ ) {
    var circle = map.drawCircle({
        lat: data.mapArray[i].lat,
        lng: data.mapArray[i].lng,
        radius: parseInt(data.mapArray[i].radius),
        strokeColor: '#'+data.mapArray[i].color,
        strokeWeight: 8,
        fillOpacity: 0,
        click: (function (e) {
            return function () {
                $('#'+modalType).modal({
                    remote: modalURL+e
                });
            };
        })(data.mapArray[i].id)
    });
    // push the circle object to the array
    circles.push(circle);
} // end loop
// remove All circles
function removeAllcircles() {
  for(var i in circles) {
    circles[i].setMap(null);
  }
  circles = [];
}
</script>
Comments