elksie5000
elksie5000

Reputation: 7752

How to toggle initial layer visibility in leaflet.js

I've created a map in leaflet.js with multiple layers but can't work out how to toggle one layer to initially appear on the map.

Here is the link

I'm sure it's fairly straightforward but just can't figure it out.

Upvotes: 5

Views: 4784

Answers (1)

iH8
iH8

Reputation: 28638

After declaring your layers you need to add one to the map, just like you did with your tilelayer. See the code below. That should work. The layercontrol will work out that the layer is visible/added to the map and check it in the list.

var map = L.map('map').setView([52.814172, -2.079479], 9);

L.tileLayer('http://{s}.tile.stamen.com/toner/{z}/{x}/{y}.jpg', {
    maxZoom: 18,
    attribution: 'Map tiles by <a href="http://stamen.com">Stamen Design</a>, under <a href="http://creativecommons.org/licenses/by/3.0">CC BY 3.0</a>. Data by <a href="http://openstreetmap.org">OpenStreetMap</a>, under <a href="http://creativecommons.org/licenses/by-sa/3.0">CC BY SA</a>.'
}).addTo(map);

// Left out layer-declarations, they are HUGE

anti_soc.addTo(map); // here it is

var overlayMaps = {
    "Anti-social behaviour" :anti_soc,
    "Criminal damage and arson": crim_dam,
    "Burglary": burg, 
    "Violence and sexual offences": viol,
    "Other theft": other_theft,
    "Vehicle crime": veh_crime,
    "Shoplifting": shoplift,
    "Public order": pub_ord, 
    "Robbery": robb,
    "Bicycle theft": bikes,
    "Drugs": drugs,
    "Theft from the person": theft_person,
    "Other crime": other_crime,
    "Possession of weapons": weap
};

L.control.layers(null, overlayMaps).addTo(map);

Upvotes: 6

Related Questions