Banner

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('http://thematicmapping.cartodb.com/api/v2/sql?q=SELECT * 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: [params.lat || -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):

http://earthatlas.info/nz/?lat=-42.4&lng=168&zoom=8



http://earthatlas.info/nz/?lat=-39.296&lng=174.065&zoom=11&layers=Springs


Easy peasy!

3 comments:

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 https://github.com/shramov/leaflet-plugins.

Anonymous said...

it would be quite useful if

https://github.com/mlevans/leaflet-hash

handled baselayers & overlays