Saturday, February 20, 2016

Switching Map Labels in Leaflet

Over the last few days I've been experimenting with Map Panes in Leafet.js. There is a nice introduction to Map Panes in the Leaflet documentation if you want to learn more about how they work in the Leaflet interactive map library.

In a post yesterday I looked at how you could use Map Panes to fade map labels in and out on top of a base map. Today I started thinking about why you might want to use this feature on a map. One reason might be to switch between two different sets of map labels. Using this feature you could remove one set of map labels and then add a completely different set of map labels to a map.

By chance a few days ago I created a set of custom map labels for an Urban Dictionary Map of San Francisco. I have now added two buttons to this map to allow you to switch between real map labels and my custom map labels based on the Urban Dictionary definition of Bay Area locations.

The Urban Dictionary Map of San Francisco has three base map layers; CartoDB's Light (no labels) map style, a custom made Urban Dictionary labels map and CartoDB's Light - Only Labels map style.

Map Panes in Leaflet allows you to order map pane layers. In the Urban Dictionary map CartoDB's Light maps is on the bottom and the two label only map styles sit on top of this layer. I then adjust the opacity of the two label map layers to switch between the two sets of labels. All three map layers are therefore present at all times. It is just that the opacity of one of the two map labels layers is always set to '0', so at anyone time you can only see the map data layer and one of the two label layers.

You might notice that I've also used JQuery to add a fade effect when you switch between the two sets of map labels. When switching between labels the opacity of the active label layer fades from '100' to '0' before switching the opacity of the other label layer to '100'.

No comments: