How can we capture change events of LayersControl component?

For example, when changing the base layer (radio buttons) or toggling an overlay on/off (checkboxes), how can we capture the change events in order to update other aspects of state in an application. Thanks in advance, open to any type of solution. Pseudo-code:

<Map>
    <LayersControl position='topright' change={this.handleLayerControlsChange}>
        <BaseLayer checked name='Map 1'>
            <TileLayer url={map1} />
        </BaseLayer>
        <BaseLayer checked name='Map 2'>
            <TileLayer url={map2} />
        </BaseLayer>
        <Overlay name='Overlay 1'>
            <LayerGroup>
                <GeoJSON data={overlayData1} />
            </LayerGroup>
        </Overlay>
        <Overlay name='Overlay 2'>
            <LayerGroup>
                <GeoJSON data={overlayData2} />
            </LayerGroup>
        </Overlay>
    </LayersControl>
</Map>

1 answer

  • answered 2020-06-02 06:56 Antismal Games

    Of course... hours and hours and it's only after posting a question that the solution is found. The map has a whenReady event (which I was already using it just wasn't in the pseudo-code) which upon looking at the Leaflet Docs on the Map Events there's a baselayerchange that can be used. Pseudo-code, that maybe helps someone else at some point:

    baseLayerChange = event => {
        console.log('baseLayerChange event', event);
    }
    
    whenReadyHandler = event => {
        const { target } = event;
        target.on('baselayerchange', this.baseLayerChange);
    }
    
    <Map whenReady={this.whenReadyHandler}>
        <LayersControl position='topright' change={this.handleLayerControlsChange}>
            <BaseLayer checked name='Map 1'>
                <TileLayer url={map1} />
            </BaseLayer>
            <BaseLayer checked name='Map 2'>
                <TileLayer url={map2} />
            </BaseLayer>
            <Overlay name='Overlay 1'>
                <LayerGroup>
                    <GeoJSON data={overlayData1} />
                </LayerGroup>
            </Overlay>
            <Overlay name='Overlay 2'>
                <LayerGroup>
                    <GeoJSON data={overlayData2} />
                </LayerGroup>
            </Overlay>
        </LayersControl>
    </Map>