Hanfei Sun
Hanfei Sun

Reputation: 47051

In Leaflet, how to change "crs" and other "Map options"?

For example, I create a map like this:

    map = L.map('map',
        {maxZoom: 17,
        attributionControl: false,
        zoomControl: false}
    )

Later, I want to change the "crs" and add a key to the map object.

I expect there might be a method called setOption, like this:

map.setOption({crs:L.CRS.BEPSG3857, customOption: true})

But unfortunately there is no such setOption method..Does anyone have ideas about how to change the Map option for a leaflet map object?

Upvotes: 6

Views: 11724

Answers (2)

jhotadhari
jhotadhari

Reputation: 31

I had a similar problem. I needed to dynamically set the scrollWheelZoom option.

I'm using L.version 1.3.1

If scrollWheelZoom option is true on map init, it will enable the corresponding Handler. Therefore we need to enable/disable the handler manually to apply the changes to the map.

List of handlers/map-properties: boxZoom, doubleClickZoom, dragging, keyboard, scrollWheelZoom, tap, touchZoom

My solution looks somehow like this:

class MyMap {

    // constructor(props) {
    //  ...
    // }

    // getMapElement(){
    //  ...
    // }

    // getBaseLayer(){
    //  ...
    // }

    initMap( mapOptions ){
        if ( ! this.map  ) {
            this.map = L.map( this.getMapElement(), mapOptions );
            this.getBaseLayer().addTo( this.map );
        }
    }

    setMapOptions( newMapOptions ){
        // loop newMapOptions object
        for ( let newMapOptionKey in newMapOptions ) {
            if( newMapOptions.hasOwnProperty(newMapOptionKey)) {
                this.setMapOption( newMapOptionKey, newMapOptions[newMapOptionKey] );
            }
        }
    }

    setMapOption( newMapOptionKey, newMapOptionVal ){
        // set map option
        L.Util.setOptions( this.map, {[newMapOptionKey]: newMapOptionVal});
        // apply option to handler
        if ( this.map[newMapOptionKey] instanceof L.Handler ) {
            if ( newMapOptionVal ) {
                this.map[newMapOptionKey].enable();
            } else {
                this.map[newMapOptionKey].disable();
            }
        }
    }

}

This works for the scrollWheelZoom option. Think it should work for all options that enable/disable handlers. So it might work for your customOption but it won't work for the crs option.

Upvotes: 3

sboulema
sboulema

Reputation: 836

Check this example on how to change crs on the fly: http://jsfiddle.net/alekzonder/qxdxqsm3/

var center = map.getCenter();

if (...) {
   map.options.crs = L.CRS.EPSG3395;
} else {
   map.options.crs = L.CRS.EPSG3857;
}

map.setView(center);

map._resetView(map.getCenter(), map.getZoom());

Upvotes: 4

Related Questions