rob.m
rob.m

Reputation: 10571

How would I clear all markers from map?

This is a function with which I add the markers to the map:

function markersresult() {
  a++;
  var addressPoints = count;

  markers = L.markerClusterGroup({
    spiderfyOnMaxZoom: false,
    showCoverageOnHover: false,
    zoomToBoundsOnClick: true,
    iconCreateFunction: function(cluster) {
      return new L.DivIcon({
        iconSize: new L.Point(20, 20)
      });
    }
  });

  for (var i = 0; i < addressPoints.length; i++) {
    var a = addressPoints[i];
    var marker = L.circleMarker(L.latLng(a[0], a[1]));
    markers.addLayer(marker);
    marker.on('click', function(e) {
      $('#results').modal('show');
      $("#results .modal-body").html("<p>1 Risultato</p><button id='goToResul' type='button' class='primary-btn'>Go to result</button>");
      var curPos = e.target.getLatLng();
      $("#longiTude").val(curPos.lng);
      $("#latiTude").val(curPos.lat);
      var lat = e.target.getLatLng().lat;
      var lng = e.target.getLatLng().lng;
    });
  }

  map.addLayer(markers);

  //count = [];
  markers.on('clusterclick', function(a) {
    console.log('cluster ' + a.layer.getAllChildMarkers().length);
    var childrenMarkerCluster = a.layer.getAllChildMarkers();
    var lat = null;
    var lng = null;
    $.each(childrenMarkerCluster, function(ind, marker) {
      var markerPosition = marker.getLatLng();
      if (lat === null && lng === null) {
        // store the coordinates of first marker
        lat = markerPosition.lat;
        lng = markerPosition.lng;
        childrenMarkerInSamePosition = true;
        $("#longiTude").val(lng);
        $("#latiTude").val(lat);
      } else {
        // if it has already gotten a result false, stop the compare  
        if (childrenMarkerInSamePosition === false) 
          return;

        if (markerPosition.lat !== lat || markerPosition.lng !== lng) {
          childrenMarkerInSamePosition = false;
        }
      }
    });

    $('#results').modal('show');
    $("#results .modal-body").html("<p>" + a.layer.getAllChildMarkers().length + " risultati</p><button id='goToResul' type='button' class='primary-btn'>Go to result</button>");
  });
}

On click on this button markers should clear:

$("#riprova").on("click", function(){
  // REMOVE MARKERS
});

I am not sure where I should do this markers.clearMarkers(); as within the button click gives me

markers.clearMarkers is not a function

Upvotes: 0

Views: 169

Answers (1)

peeebeee
peeebeee

Reputation: 2618

$("#riprova").on("click", function(){
      markers.clearLayers();
    });

Docs at:

https://github.com/Leaflet/Leaflet.markercluster#adding-and-removing-markers

Upvotes: 1

Related Questions