OpenLayers 3 introduction

In one of my recent projects I had the pleasure to develop a tool that allows the users to use different geographical maps (Bing Maps, OpenStreetMap, …) and also allow to drawing on these maps. To accomplish these requirements I used OpenLayers 3. With a blog series starting with this blog post, I want to share my experience.

What is OpenLayers 3?

OpenLayers 3 is a JavaScrip library you can use to show map data in web browsers. With the ability to extend the map with drawing or calculating features OpenLayers 3 can be used to build tools around the original maps.

Including the map in your website or web application

For this blog series I will implement a little example application that will be extended during the series. It will contains all features I describe in the series. You can find the code of the application on GitHub. This app at least will be able to show different data sources (Bing, OpenStreetMap), drawing on the map and calculating differences between two coordinates. 

To include OpenLayers 3 you have to integrate two files. Both can be downloaded on the website of OpenLayers 3.

  • ol.js (or ol-debug.js)
  • ol.css

To create a map you have to use an empty div with an id into your HTML:

<!doctype html>  
<html lang="en">  
<head>  
    <title>OpenLayers 3 series</title>
    <link rel="stylesheet" href="build/style.css">
</head>  
<body>  
    <h2>OpenLayers 3 series example</h2>
    <div id="map" class="map"></div>

    <script type="text/javascript" src="build/script.js"></script>
</body>  
</html>  

While the div will be used as a rendering target (where the map will be shown), a few lines of JavaScript are needed, to initialize the OpenLayers 3 map.

var map = new ol.Map({  
    target: 'map',
    layers: [
        new ol.layer.Tile({
            // Using OpenStreetMap to show a map
            source: new ol.source.OSM() 
        })
    ],
    view: new ol.View({
        // Set the default center of the map view
        center: ol.proj.fromLonLat([0, 0]),
        // Set default zoom
        zoom: 4 
    })
});

To render the map on the div you have to set the target -property. With the target -property you define the element id that is used to locate the element where the map will be rendered. An OpenLayers 3 map is built on different layers. A layer is the visual representation of map data. In my example I will use only one layer to show a map. Each layer needs a source to know where the data is coming from that the layer has to display. There are different sources you can use with OpenLayers 3. Let’s use OpenStreetMap for now. But you can also use other maps like Bing Maps, of course.

source: new ol.source.BingMaps({  
            // Redeem your API key on the linked website
            key: 'YourAPIKeyHere', 
            imagerySet: 'Road'
        })

Defining layers is not enough to show the map. You also have to define a view. Creating a view offers you the possibility to set a center of the visible map section (your latitude and longitude coordinates) and a zoom level.

But be careful! The zoom level depends on the map you use. Not every map supports every zoom level.

Side note: If you work with coordinates in OpenLayers 3 you always have to use an array of  two numbers [latitude, longitude].

Locate current user position

To find the current user position I use the HTML5 geolocation feature. OpenLayers 3 includes a helper class to access all geolocation features. To create a valid geolocation object you have to pass two properties to the constructor of the helper class. The first property is to set the projection of the location.

Projection is a method to recalculate the earth’s curved surface into flat 2-D model. This is necessary to display GPS coordinates on the right place. Dependent on the target map there are different projections. For more information about projections look [here](https://en.wikipedia.org/wiki/Map_projection

The second parameter tracking  is used to activate the user tracking. If this parameter is set to false the geolocation will not get the current user position automatically respectively the position change event is not fired.

var geolocation = new ol.Geolocation({  
    // Get the current map projection
    projection: map.getView().getProjection(), 
    // Track the user position
    tracking: true
});

To change the position on the map it is necessary to listen to the geolocation change event and set a new center of the view. I also set a higher zoom level when the user position is located. OpenLayer 3 uses the Google Closure Library internally so I use it too to be compliant to the OpenLayers 3 code. The Closure library is available on the global variable goog.

goog.events.listen(geolocation, goog.events.EventType.CHANGE, function (event) {  
    map.getView().setCenter(geolocation.getPosition());
    map.getView().setZoom(10);
});

Run the example

To run my example you have to execute two commands:

  • npm run install (installs the dependencies)
  • npm run start (starts the application)

To build and run my application Gulp is my choice of tooling. For a good Gulp introduction read the blog series from my colleague Thorsten Hans. Running the Gulp file will start a webserver and the map example will be accessible under http://localhost:9090.
Voila!

map

That’s it for the first installment.
In the next blogpost I will show you how to draw on the map.
Stay tuned.