Javascript – How to clear leaflet map of all markers and layers before adding new ones

google mapsjavascriptleafletmaps

I have the fallowing code:

map: function (events) {
    var arrayOfLatLngs = [];
    var _this = this;

    // setup a marker group
    var markers = L.markerClusterGroup();

    events.forEach(function (event) {
        // setup the bounds

        // create the marker
        var marker = L.marker([, event.location.lng]);


        // add marker

    // add the group to the map
    // for more see;

    var bounds = new L.LatLngBounds(arrayOfLatLngs);;;

I initially call this function and it will add all events to the map with markers and clusters.

at some lather point i pass in some other events, the map will zoom in to the new events but the old ones are still on the map.

I've tried; and some other stuff, but I can't get the old markers to disappear

Any ideas?

Best Answer

If you want to remove all the current layers (markers) in your group you can use the clearLayers method of L.markerClusterGroup(). Your reference is called markers so you would need to call: