Search code examples
leafletangular-leaflet-directive

Leaflet L.Icon marker not removing on Map reload


Map contains two types of markers Circle icon is added by:

      let circle = new customCircleMarker([item.latitude, item.longitude], {
        color: '#2196F3',
        fillColor: '#2196F3',
        fillOpacity: 0.8,
        radius: radM,
        addressId: item.address_id
      }).bindTooltip(`Address: <b>${item.address}</b><br/>
                   Patients from this address: <b>${item.total_patients}</b><br/>
                   Production: <b>$${item.total_production}</b><br/>`)
        .addTo(this.mapInstance).on('click', this.circleClick);

Icon marker is added in the following method:

// create marker object, pass custom icon as option, pass content and options to popup, add to map

      // create marker object, pass custom icon as option, pass content and options to popup, add to map
      L.marker([item.latitude, item.longitude], { icon: chartIcon })
        .bindTooltip(`Address: <b>${item.address}</b><br/>
                   Patients from this address: <b>${item.total_patients}</b><br/>
                   Production: <b>$${item.total_production}</b><br/>`)
        .addTo(this.mapInstance).on('click', this.circleClick);

On clearing map Icon marker is not removed

Map clearing function:

if (this.mapInstance) {
  for (let i in this.mapInstance._layers) {
    if (this.mapInstance._layers[i]._path !== undefined) {
      try {
        this.mapInstance.removeLayer(this.mapInstance._layers[i]);
      } catch (e) {
        console.log('problem with ' + e + this.mapInstance._layers[i]);
      }
    }
  }
}

Solution

  • You're checking for a _path property before removing. It will skip the L.Marker layers because they don't have a _path property, only vector layers (extended from L.Path) do.

    If you ever need to delete only certain layer types from your map you are best off by grouping them in a grouping layer like L.LayerGroup or L.FeatureGroup and then using their clearLayers method:

    var layerGroup = new L.LayerGroup([
        new L.Marker(...),
        new L.CircleMarker()
    ]).addTo(map);
    
    layerGroup.clearLayers();
    

    If that is not an option you could iterate the map's layers and then check the instance of the layer:

    function customClearLayers () {
        map.eachLayer(function (layer) {
            if (layer instanceof L.Marker || layer instanceof L.CircleMarker) {
                map.removeLayer(layer);
            }
        });
    }