Control.Layers addBaseLayer and addOverlay do not seem to function correctly for me

1k Views Asked by At

I've been following recommendations I've seen on here to add layer controls using the addBaseLayer and addOverlayLayer functions, however the resulting object does not seem to be recognized correctly by the map. I get no controls and when I try to click on the map control, I get a flickering cursor and no control panel. I used the ngx-leaflet demo and modified the code to match what I was doing in my application and got the same result.

My html looks like this:

    <div leaflet style="height: 300px;"
        [leafletOptions]="options"
        [leafletLayersControl._layers]="layers"
        [leafletLayersControl]="layersControl">
    </div>

My .ts looks like this:

    layersControl = new Control.Layers();
    ...
    this.layersControl.addBaseLayer(this.LAYER_OSM.layer, 'Open Street Map');
    this.layersControl.addBaseLayer(this.LAYER_OCM.layer, 'Open Cycle Map');
    this.layersControl.addOverlay(this.circle.layer, "Circle");
    this.layersControl.addOverlay(this.square.layer, "Square");
    this.layersControl.addOverlay(this.polygon.layer, "Polygon");
    this.layersControl.addOverlay(this.marker.layer, "Marker");

And this results in the following layersControl object: My layersControl

By comparison, this was the code from the demo:

    layersControl = {
        baseLayers: {
            'Open Street Map': this.LAYER_OSM.layer,
            'Open Cycle Map': this.LAYER_OCM.layer
        },
        overlays: {
            Circle: this.circle.layer,
            Square: this.square.layer,
            Polygon: this.polygon.layer,
            Marker: this.marker.layer,
            GeoJSON: this.geoJSON.layer
        }
    };

Which resulted in this layersControl object: enter image description here

Is this simply an issue with my usage, or a bug?

Thanks!

1

There are 1 best solutions below

0
On

It is an issue with your usage.

ngx-leaflet does not expect a Leaflet Layers Control instance to be bound to its [leafletLayersControl] attribute, but a plain object with baseLayers and overlays dictionaries, as shown in the example you mention.

If you really need to use a Leaflet Layers Control instance, you should retrieve the underlying mapObject, then use it as per Leaflet API, instead of trying to feed it to ngx-leaflet wrapper.

But another more Angular-like approach would simply be to add data to the plain object (in case you want to dynamically add base layers / overlays), and Angular and ngx-leaflet will take care of tracking those changs and update the map (and its Layers Control) accordingly.