1

Please note that i am using @asymmetrik/ngx-leaflet-draw for Angular. I'm configuring a map where the user can draw either rectangles or polygons. I then save these to a layerGroup based on the onDrawCreated event, this is working perfectly.

I'm also aiming to delete layers based on the onDrawDeleted event, but this is for some reason not working. What i'm finally doing in the application is to save the data and convert it to GeoJSON. Then display it in the console for troubleshooting-purposes.

Component HTML:

<button (click)="checked = !checked">Edit Mode</button>
<button (click)="onSave()">Save</button>
<div id="image-map" 
leaflet 
[leafletOptions]="options" 
[leafletLayersControl]="layersControl"
    (leafletMapReady)="onMapReady($event)">
    <div *ngIf="checked" 
    leafletDraw 
    [leafletDrawOptions]="drawOptions" 
    (leafletDrawCreated)="onDrawCreated($event)" 
    (leafletDrawDeleted)="onDrawDeleted($event)">
    </div>
</div>

Part of the map and leaflet draw component:

  zones = L.featureGroup();

  onDrawCreated(e: any) {
    this.zones.addLayer(e.layer);
    console.log('Draw Created Event!', e);
    console.log(this.zones.getLayers());
  }

  onDrawDeleted(e: any) {
    this.zones.removeLayer(e);
    console.log('Draw Deleted Event!', e);
    console.log(this.zones.getLayers());
  }

  onSave() {
    const data = this.zones.toGeoJSON();
    console.log(data);
  }

Based on the documentation and other similar questions, the above code should work. But i imagine i'm missing something simple.

kboul
  • 13,836
  • 5
  • 42
  • 53
Koronag
  • 157
  • 1
  • 15
  • So your problem is that they are not removed from the map, from the array or from both? Because to remove them from the map is a library behavior. Does not need extra code to be accomplished. – kboul Oct 03 '19 at 11:06
  • Sorry i should have elaborated. They do indeed dissappear from the map, but not from the array unfortunately. – Koronag Oct 03 '19 at 11:15

1 Answers1

4

Iterate over the deleted layers to remove the deleted layer. If it is only one then it will be removed.

onDrawDeleted(e: any) {
    e.layers.eachLayer(layer => {
      this.zones.removeLayer(layer);
    });
    console.log("Draw Deleted Event!", e);
    console.log(this.zones.getLayers());
  }

Demo

kboul
  • 13,836
  • 5
  • 42
  • 53
  • 1
    This works perfectly man. Thank you very much. I thought it would work with this.zones.eachLayer, but of course you have to iterate over the ones you actually deleted and then connect them to the existing layers in this.zones. – Koronag Oct 04 '19 at 01:20
  • YESSS!!! Thanks! Made perfect sense. It gives you as list of those you deleted, then you just delete those layers. RemoveLayer was the key for me. – vr_driver Jul 06 '21 at 13:00