vincent3569
vincent3569

Reputation: 457

how to use layers control with leaflet and leaflet-provider

I want to dispaly layers control when leaflet and leaflet-provider are used. It works well but on load, the map used is not selected in the control. note that I can select the default map (and of course, nothing changes) and I can choose the other map (and I switch to this map).

Why the default map is not selected in the control ? I don't know if there an issue or if I don't use the appropriate code.

you can see my code on plunker here: http://plnkr.co/edit/d4ycVbdVRGoxE9h8svQe

var map = L.map('osm_map', {
    zoom: 4,
    zoomControl: false,
    minZoom: 2,
    maxZoom: 18
});
var baseMaps = {
    'OpenTopoMap': L.tileLayer.provider('OpenTopoMap'),
    'OpenStreetMap.France': L.tileLayer.provider('OpenStreetMap.France')
};
L.tileLayer.provider('OpenTopoMap').addTo(map);
L.control.layers(baseMaps).addTo(map);
L.control.zoom({position: 'topleft'}).addTo(map);
L.marker([57.150,-6.100]).addTo(map);
L.marker([57.500,-6.450]).addTo(map);
map.fitBounds([
    [57.150,-6.100], [57.500,-6.450]
]);

thanks for your help

Upvotes: 1

Views: 636

Answers (1)

ghybs
ghybs

Reputation: 53205

Why the default map is not selected in the control?

Because you actually create 2 Tile Layers, even if they render exactly the same.

For the Leaflet Layers Control to detect that one of its base maps is already added to the map (the "default" base map), you have to add the exact same layer object.

var defaultBaseMap = L.tileLayer.provider('OpenTopoMap')
defaultBaseMap.addTo(map)
var baseMaps = {
  'OpenTopoMap': defaultBaseMap,
  'OpenStreetMap.France':  L.tileLayer.provider('OpenStreetMap.France')
};

Upvotes: 3

Related Questions