consulting and development

maps, GIS and geospatial software

Quick-n-dirty layer switcher for OpenLayers 3

No layer switcher?

I’ve been working on a few demos lately – partly in order to test out some options for 3D map rendering on the web, partly in order to get used to OpenLayers 3 which is very different from version 2 to say the least!

After trying out some basic stuff, it was time to add more layers and an interface to switch them on/off. I was very surprised to learn that this crucial functionality for a map is not there in ol3. Well, I’ve made more complicated stuff before, so I figured I’ll mock up a quick one in order to get more familiar with ol3 along the way.

Here’s what it looks like – base layers first, overlays below:


And here’s a link to the javascript file, LayerSwitcher.js. It’s a class which can be instantiated with a few options:

div – {Element | String} Where to render, if not provided, will be added to document.body.
map – {ol.Map} The map instance to control layers on.
cssPath – {String} Path of alternative css file to load.

E.g. like this:

I soon ran in to other surprising challenges – see next page: