Search code examples
leafletangular5ngx-leaflet

Change leafletLayers after a dragend event


I need to delete all the leafletLayers and add others after a 'dragend' event. So, i proceeded as below :

mapParent.component

template: '<app-map [leafLetmarkers]="markers" (refreshMap)="refresh($event)"></app-map>'

...

markers: L.Layer[] = [];
refresh(position) {
    //delete all markers
    var markers = []; 
    //set the new markers
    this.markers= newMarkers;
}

map.component

template: '<div leaflet style="height: 100%;"
                [leafletOptions]="options"
                [leafletLayers]="markers"
                (leafletMapReady)="onMapReady($event)">
           </div>'

...

@Input('leafLetmarkers') markers: L.Layer[];
@Output() refreshData = new EventEmitter<L.LatLng>();

onMapReady(map: L.Map) {
    map.on('dragend', e => this.refreshMap.emit(map.getCenter()));
}

Is this the right way to do this ?

Regards.


Solution

  • Your general approach is correct.

    The issue you might run into is that you are changing a bound property this.markers inside of a callback from Leaflet. Leaflet callbacks are outside of the Angular zone (Angular doesn't try to track changes outside of its zone). This is a design choice on the part of ngx-leaflet to prevent excessive change detection that might impact application performance.

    The solution is to manually trigger change detection:

    fitBounds: any = null;
    circle = circle([ 46.95, -122 ], { radius: 5000 });
    
    // Inject the Change Detector into your component
    constructor(private changeDetector: ChangeDetectorRef) {}
    
    ngOnInit() {
    
        // The 'add' event callback happens outside of the Angular zone
        this.circle.on('add', () => {
    
            // Because we're outside of Angular's zone, this change won't be detected
            this.fitBounds = this.circle.getBounds();
    
            // But, it will if we tell Angular to detect changes 
            this.changeDetector.detectChanges();
    
        });
    }
    

    For more details, you can see this section of the ngx-leaflet README: https://github.com/Asymmetrik/ngx-leaflet#a-note-about-change-detection