Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to toggle initial layer visibility in leaflet.js

Tags:

leaflet

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.

like image 687
elksie5000 Avatar asked Nov 21 '14 07:11

elksie5000


People also ask

How do you toggle the visibility of a layer?

Click the eye icon next to a layer to toggle the visibility on or off. You can also click-and-drag up or down on multiple eye icons to toggle the visibility of multiple layers.

What is Tilelayer in leaflet?

Used to load and display tile layers on the map, implements ILayer interface.

How do you add an overlay to a leaflet?

Image OverlayStep 1 − Create a Map object by passing a <div> element (String or object) and map options (optional). Step 2 − Create a Layer object by passing the URL of the desired tile. Step 3 − Add the layer object to the map using the addLayer() method of the Map class. Step 4 − Create the image overlay using L.


1 Answers

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);
like image 139
iH8 Avatar answered Oct 19 '22 16:10

iH8