在dragend事件之后更改leafletLayers

时间:2018-02-15 14:38:34

标签: leaflet angular5 ngx-leaflet

我需要删除所有的leafletLayers并在“dragend”之后添加其他的。事件。所以,我继续如下:

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()));
}

这是正确的方法吗?

问候。

1 个答案:

答案 0 :(得分:1)

您的一般方法是正确的。

您可能遇到的问题是您正在从Leaflet更改回调内的绑定属性this.markers。 Leaflet回调在Angular区域之外(Angular不会尝试跟踪其区域之外的更改)。这是ngx-leaflet的一个设计选择,可以防止可能影响应用程序性能的过度变化检测。

解决方案是手动触发变更检测:

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();

    });
}

有关详细信息,您可以看到ngx-leaflet自述文件的这一部分: https://github.com/Asymmetrik/ngx-leaflet#a-note-about-change-detection