DEV Community

Richard Greenwood
Richard Greenwood

Posted on

Getting Started with OpenLayers 5

January 2019

OpenLayers is an advanced, feature rich client-side JavaScript map rendering library. It is Open Source and standards compliant. If you want to do sophisticated interactive mapping in a web browser you owe it to yourself to check out Openlayers. It's mature (I've been using it since 2006) but it's not "old" - it is a thoroughly modern code base with cutting edge functionality.

Getting started with OpenLayers can be intimidating. The standard on-ramp is the examples page with about 150 examples and a nice search tool at the top. The problem with the current version (5.3) is that there is an assumption of a level of understanding that might be a barrier to entry. Despite the nice "copy" icon above the code in the examples, you can not just paste into your editor and have working code to play with.

There is a little editing required to get the examples to work. This isn't because the examples are broken, but because the openLayers library offers a lot of flexibility. There are at least three ways to use OpenLayers in your app and to get the copy-and-paste examples working:

  1. Include the full OpenLayers library and call its constructors and methods.
  2. Use a bundler like webpack to bundle your code with the required OpenLayers modules.
  3. Use the browser's native ES6 module support.

The first method is easiest. But OpenLayers has about 78,000 lines of code (not minimized, including comments) and your app is never going to use all of its functionality and features. The second method is the developers recommended route. A bundler will only include the OpenLayers modules that your app requires and provide additional optimizations. The third method is possible because OpenLayers uses ES6 compliant export/import syntax. It's probably not a good way to go for a production app because OpenLayers has nearly 700 modules and even if you are using some fraction of those and even if you are using http2, it's still a whole lot of modules. But It appeals to me because it seems so modern and "pure".

Let's take a look at what needs to be done with the OpenLayers 5.3.0 simple.html example to use each of the three approaches. The JavaScript looks like:

      import Map from 'ol/Map.js';
      import View from 'ol/View.js';
      import TileLayer from 'ol/layer/Tile.js';
      import OSM from 'ol/source/OSM.js';

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

But if you have pasted the example into your editor and then open the file in your browser you will get the error: "Uncaught SyntaxError: Unexpected identifier"

To get it working with the first method you need to include the full OpenLayers library and remove the four import statements. The full library is available via cdn (not recommended for production)

<script src="https://cdn.rawgit.com/openlayers/openlayers.github.io/master/en/v5.3.0/build/ol.js"></script>

or better, download the full distribution v5.3.0.zip and point the script src to your copy. Then comment or remove the imports as shown below.

     <!-- add script element pointing to full openlayers -->
    <script src="path/to/where/you/downloaded/ol.js"></script>
    <script>
      /*  // remove imports
      import Map from 'ol/Map.js';
      import View from 'ol/View.js';
      import TileLayer from 'ol/layer/Tile.js';
      import OSM from 'ol/source/OSM.js';
      */

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

So pretty easy! It's a good way to explore OpenLayers with minimal effort.

But we can do better. By using an ES6 module bundler like Webpack, Rollup or Parcel you can merge your own modules with OpenLayers', build smaller distributions, and code in a more modern environment. And this is the recommended way to develop production apps with OpenLayers. The next version of OpenLayers, due out in February 2019, will have working examples that use this method. But if you can't wait, read on!

Webpack does not use the v5.3.0.zip files. Webpack uses the source modules which are installed with npm.

There are great starter guides on github for:
OpenLayers + Webpack
OpenLayers + Rollup
OpenLayers + Parcel
However the OpenLayers 5.3.0 examples still won't quite work out of the box with these. Again just a few minor edits will get you going with the examples.

Rather than use any of the starter packages above we'll use webpack in the most basic possible configuration. I'll assume that you know more about webpack than I do (most people do) and that you have nodejs installed. For the most basic setup:

mkdir ol-test && cd ol-test
npm install ol
npm install --save-dev webpack webpack-cli
mkdir src

Paste the JavaScript from the simple.html example into a new JavaScript file named "index.js" and save it to src/ directory. Because Map, View, TileLayer, and OSM are imported, the "ol.", "ol.layer", and "ol.source" prefixes are unnecessary and need to be removed. The edited JavaScript src/index.js file should look like:

      import Map from 'ol/Map.js';
      import View from 'ol/View.js';
      import TileLayer from 'ol/layer/Tile.js';
      import OSM from 'ol/source/OSM.js';

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

Run webpack to bundle src/index.js with the imported OpenLayers modules. (Normally you would use a package.json file with a "scripts" section but our focus is just on making the OpenLayers examples work)

node_modules/.bin/webpack

By default webpack looks for ./src/index.js for its source and writes the bundled output to ./dist/main.js so remove the inline Javascript from simple.html and add a script element that points to your bundle:

    <script src="dist/main.js"></script>

With a little luck you'll see a map when you open simple.html in your browser.

I'll describe the third way to work with OpenLayers, natively loading the modules in a browser, in a future post. This method is probably not practical for production, at least not at this point in web evolution. Older browsers can not import ES6 modules, and the number of modules required would probably be a performance hit. But the fact that it can be done shows how modern and clean the OpenLayers code base is, and it's really fun to play with.

Discussion (0)