OpenLayers 3+: How to add controls

Antonis Christofides
GIS tips
Published in
2 min readJun 20, 2017

Pretty much the simplest way to create a map is this:

var map = new ol.Map({
target: 'map',
layers: [new ol.layer.Tile({ source: new ol.source.OSM() })],
view: new ol.View({ center: [0, 0], zoom: 2 })
});

We have a parameter target: 'map'. This means the map will be placed in an otherwise empty <div> with id=map. For example, for making tests you could use <div id='map' style='width: 640px; height: 480px'></div>. In your final web page you need to do this better, but this is an HTML+CSS issue that has nothing to do with OpenLayers.

The map will have three controls (if they aren’t visible you probably have failed to include ol.css):

  1. A zoom control on the top left;
  2. An attribution control on the bottom right;
  3. A rotation control. It is on the top right, but it is invisible until you use Alt+Shift+drag to rotate the map.

If, instead, we use the following definition, the map will only have a scale line control instead:

var map = new ol.Map({
target: 'map',
layers: [new ol.layer.Tile({ source: new ol.source.OSM() })],
view: new ol.View({ center: [0, 0], zoom: 2 }),
controls: [new ol.control.ScaleLine]
});

(You can still zoom with the mouse wheel, and you can still rotate the map with Alt+Shift+drag, but there is no visible zoom control and no “revert to north” control.)

What if you want to keep the three default controls in addition to the scale line control?

var map = new ol.Map({
target: 'map',
layers: [new ol.layer.Tile({ source: new ol.source.OSM() })],
view: new ol.View({ center: [0, 0], zoom: 2 }),
controls: ol.control.defaults().extend([new ol.control.ScaleLine])
});

What if, from the default controls, you want to keep only zoom, and also add a scale line?

var map = new ol.Map({
target: 'map',
layers: [new ol.layer.Tile({ source: new ol.source.OSM() })],
view: new ol.View({ center: [0, 0], zoom: 2 }),
controls: ol.control.defaults({
rotate: false,
attribution: false
}).extend([new ol.control.ScaleLine])
});

Of course you can also do it explicitly like this:

var map = new ol.Map({
target: 'map',
layers: [new ol.layer.Tile({ source: new ol.source.OSM() })],
view: new ol.View({ center: [0, 0], zoom: 2 }),
controls: [
new ol.control.Zoom(),
new ol.control.ScaleLine()
]
});

This is so much simpler that you shouldn’t use ol.control.defaults() for anything but extending.

--

--

Antonis Christofides
GIS tips

I help scientists and engineers bring their models to the web