I am using Angular 5 + ngx-leaflet on my web page to display map with layer data from WMS server.
parent component html
<div class="majorContainer">
<app-leftcol (leftcolUpdate)="leftColChange($event)"></app-leftcol>
<div class="mainRightContainer">
<app-mapcomponent></app-mapcomponent>
</div>
</div>
parent.component.ts
export class MajorComponent implements OnInit {
@Output() updateMapLayer = new EventEmitter<any>();
constructor() { }
ngOnInit() {
}
leftColChange($event) {
console.log('emit to leaflet layer');
this.updateMapLayer.emit({newModelName: $event.newModelName, view:
$event.view});
}
}
map component html:
<div class="mapContainer">
<div id="mapid"
leaflet
[leafletOptions]="options"
[leafletLayers]="layers"
[leafletLayersControl]="layersControl"
(leafletMapReady)="initMap($event)"
(updateMapLayer)="updateLayer($event)">
</div>
</div>
map.component.ts:
export class MapComponent implements OnInit {
constructor() { }
options = {...};
layers = [ ... ];
layersControl = {
overlays: {
'Map WMS Layer": tileLayer.wms('http://...', {version: '1.1.1', newModelName: 'default', view: 'default', year: '2018');
}
};
ngOnInit() {}
initMap(map: Map) {...}
updateLayer($event) {
const updateOptions = {version:'1.1.1',newModelName:$event.newModelName,view:$event.view,year:$event.year};
this.layersControl.overlays['Map WMS Layer'].setParams(updateOptions);
this.layersControl.overlays['Map WMS Layer'].redraw();
}
}
What I want to achieve: When the value in left column changes, the WMS URL in the map layer will be updated and refresh.
I tried to use EventEmitter to parse the updated value to parent component and call the child map component to update WMS layer, but it is not working. Is it because the approach is not correct?
Thank you.
You can't modify the parameters of an existing layer like that. You should treat the map layers as immutable and not reusable between maps. In this case, you should create a new layer with the new URL and then modify the [leafletLayers] array to have the new layer.
If you wanted to change the layers in the layersControl.overlays
map, you'd need to modify the key name, because change detection won't work if all you're changing is the layer to which an existing key refers. But, if you had your event pass the new name of the layer along with the new layer information, you could do something like the following:
export class MapComponent implements OnInit {
constructor() { }
options = {...};
layers = [ ... ];
layersControl = {
overlays: {
'Map WMS Layer": tileLayer.wms('http://...', {version: '1.1.1', newModelName: 'default', view: 'default', year: '2018');
}
};
ngOnInit() {}
initMap(map: Map) {...}
updateLayer($event) {
let overlays = {};
overlays[$event.newKey] = tileLayer.wms('http://...', {
version: '1.1.1',
newModelName: $event.newModelName,
view: $event.view,
year: $event.year
});
this.layersControl.overlays = overlays;
}
}