Layer control in Leaflet powered maps

In this post we will demonstrate using the leaflet layer control. The layer control allows the map user to switch on and off base maps and vector layers on the map

Our overlay will be geojson point features and our base layers will be map tiles from openstreetmap and Stamen maps.

 

First, we prepare the html webpage and the map tiles that would form the base maps in the Layer control.

Next we write out geojson point features – ‘var sites’ and put them in a new layer group – ‘var points’.

The layer groups will be put just after the <script> on the page-(insert in the space Indicated by the red ? in the code above).

 

// groups all the features into one layer

var points = new L.LayerGroup(sites);
// Add a function to enable popup on each feature based on value 
contained in the property “Name”

function onEachFeature(feature, layer){
if(feature.properties&&feature.properties.Name) {
layer.bindPopup(feature.properties.Name);}}

var sites = [{
	"type": "Feature","properties": {"Name":  "<h4 style='color:red';>LocNo: 3756</h4><br>Country:nigeria<br>Type:Onshore facility"
	}, "geometry": {"type": "Point","coordinates": [7.73, 6.44]
	}}, {
	"type": "Feature", "properties": { "Name": "Loc 874” 
	}, "geometry": {"type": "Point", "coordinates": [4.00, 3.22]
	  }}];
//styling the features with CSS
var style = {
fillColor: "yellow",
color: "red"
	};
//converting the default markers to circular markers, 
drawing the geojson on the map and adding the style and popup features
to the features 

L.geoJson(dim, {onEachFeature,
pointToLayer: function(feature, latlng) {
return L.circleMarker(latlng, style); }}
).addTo(points);

 

In the var map object, add points as an additional layer- highlighted in yellow.

 

var map = L.map(‘map’, {
center: [7.75, 3.50],
zoom:  6,
layers: [basemap, points]
    });

 

Next, give the basemap and top layers labels for the layer control.

 

var basemap = {"base": basemap, "gray": gray };
var Toplayer = {"sites": points};
Add the layer control and layers to the map.

L.control.layers(basemap, Toplayer).addTo(map);
See live example of web map at 
https://mayotunde.github.io/layerscontrol

Download the plain text version of the source code
by clicking the link below:
 
https://www.dropbox.com/s/24sikwjuuaoh5wc/Layer%20control%20in%20Leaflet%20powered%20maps.txt?dl=0
Example source code below:

Document4-001

 

Thank you for following the blog. We welcome your comments and feedback.

Advertisements

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out / Change )

Twitter picture

You are commenting using your Twitter account. Log Out / Change )

Facebook photo

You are commenting using your Facebook account. Log Out / Change )

Google+ photo

You are commenting using your Google+ account. Log Out / Change )

Connecting to %s