3.1. Displaying a Scale Line

Another typical widget to display on maps is a scale bar. ol3 provides an ol.control.SaleLine for just this.

3.1.1. Creating a ScaleLine Control

Tasks

  1. Open the map.html in your text editor.

  2. Somewhere in the map config, add the following code to create a new scale line control for your map:

    controls: ol.control.defaults().extend([
      new ol.control.ScaleLine()
    ]),
    
  3. Save your changes and open map.html in your browser: http://localhost:8080/ol_workshop/map.html

    ../_images/scaleline1.png

    A default scale bar in the bottom left-hand corner

3.1.2. Moving the ScaleLine Control

You may find the scale bar a bit hard to read over the imagery. There are a few approaches to take in order to improve scale visibility. If you want to keep the control inside the map viewport, you can add some style declarations within the CSS of your document. To test this out, you can include a background color and padding to the scale bar with something like the following:

.ol-scale-line {
  background: black;
  padding: 5px;
}

However, for the sake of this exercise, let’s say you think the map viewport is getting unbearably crowded. To avoid such over-crowding, you can display the scale in a different location. To accomplish this, we need to first create an additional element in our markup and then tell the scale control to render itself within this new element.

Tasks

  1. Create a new block level element in the <body> of your page. To make this element easy to refer to, we’ll give it an id attribute. Insert the following markup somewhere in the <body> of your map.html page. (Placing the scale element right after the map viewport element <div id="map"></div> makes sense.):

    <div id="scale-line" class="scale-line"></div>
    
  2. Now modify the code creating the scale control so that it refers to the scaleline element:

    controls: ol.control.defaults().extend([
      new ol.control.ScaleLine({target: document.getElementById('scale-line')})
    ]),
    
  3. Save your changes and open map.html in your browser: http://localhost:8080/ol_workshop/map.html

  4. You also need a bit of css for the scale line to show up in the right place:

    .scale-line {
      position: absolute;
    }
    .ol-scale-line {
      position: relative;
    }
    
  5. Now save your changes and view map.html again in your browser: http://localhost:8080/ol_workshop/map.html

    ../_images/scaleline2.png

    A scale line control outside the map viewport.

Table Of Contents

Previous topic

3. Working With Interactions and Controls

Next topic

3.2. Selecting Features