Monday 8 October 2012

How to control your Leaflet map with URL parameters

I needed a way to control the appearance for my Leaflet map of New Zealand, especially when embedding a map with an iframe. Leaflet have no native support for URL parameters for, like the Permalink control for OpenLayers (there is a plugin + Leaflet-hash). This blog post will show you how you can add support for URL parameters for map position (latitude/longitude), zoom level and active layers.

First, I'm defining my layers in an JavaScript object:

var layers = {
  'Seafloor': L.tileLayer('tiles/nz-seafloor/{z}/{x}/{y}.png'),
  'Topographic': L.tileLayer('tiles/nz-topo/{z}/{x}/{y}.png'),
  'Tour': L.cartoDB(' * FROM new_zealand_tour')

You can use the same object to populate the Leaflet layers control. Next, I'm extracting the URL parameters with a regular expression (from Papermashup):

var params = {};
window.location.href.replace(/[?&]+([^=&]+)=([^&]*)/gi, function(m, key, value) {
  params[key] = value;

All URL parameters are now stored as key/value pairs in the params object. We need to create an array of active map layers:

if (params.layers) {
  var activeLayers = params.layers.split(',').map(function(item) {    
    return layers[item];

The array map function will create a new array with a reference to the visible layers on the map. Please note that the map function is not supported in Internet Explorer < 9 (you can easily rewrite the function with a for loop to support this browser).

We can now create a map with our URL parameters:

var map = new L.Map('map', {
  center: [ || -41.2728, params.lng || 173.2996],
  minZoom: 4,
  maxZoom: 12,  
  zoom: params.zoom || 6,
  layers: activeLayers || [layers.Seafloor, layers.Topographic]

I'm using the Logical OR (||) operator to add default values. Lastly, I'm adding my map layers to the layers control, allowing users to toggle the visibility:

L.control.layers({}, layers).addTo(map);

This is the full example:

We can now control the map med URL parameters like (the code in this example is changed to support base layers and overlays):

Easy peasy!


Anonymous said...

Thanks so much. That was the missing link.. for me, getting the overlays in a url hash. happy travels..

Bryan McBride said...

There is an OL style Permalink plugin for Leaflet at

Anonymous said...

it would be quite useful if

handled baselayers & overlays

Alexander Rutz said...

Is there still no native leaflet-support for this? I felt all the solutions that are around seemed very fragile …