Home Web-development OpenLayers 3: Beginner's Guide

OpenLayers 3: Beginner's Guide

By Thomas Gratier , Paul Spencer , Erik Hazzard
books-svg-icon Book
Subscription
$10 p/m for first 3 months. $15.99 p/m after that. Cancel Anytime!
What do you get with a Packt Subscription?
This book & 7000+ ebooks & video courses on 1000+ technologies
60+ curated reading lists for various learning paths
50+ new titles added every month on new and emerging tech
Early Access to eBooks as they are being written
Personalised content suggestions
Customised display settings for better reading experience
50+ new titles added every month on new and emerging tech
Playlists, Notes and Bookmarks to easily manage your learning
Mobile App with offline access
What do you get with a Packt Subscription?
This book & 6500+ ebooks & video courses on 1000+ technologies
60+ curated reading lists for various learning paths
50+ new titles added every month on new and emerging tech
Early Access to eBooks as they are being written
Personalised content suggestions
Customised display settings for better reading experience
50+ new titles added every month on new and emerging tech
Playlists, Notes and Bookmarks to easily manage your learning
Mobile App with offline access
What do you get with eBook + Subscription?
Download this book in EPUB and PDF formats, plus a monthly download credit
This book & 6500+ ebooks & video courses on 1000+ technologies
60+ curated reading lists for various learning paths
50+ new titles added every month on new and emerging tech
Early Access to eBooks as they are being written
Personalised content suggestions
Customised display settings for better reading experience
50+ new titles added every month on new and emerging tech
Playlists, Notes and Bookmarks to easily manage your learning
Mobile App with offline access
What do you get with a Packt Subscription?
This book & 6500+ ebooks & video courses on 1000+ technologies
60+ curated reading lists for various learning paths
50+ new titles added every month on new and emerging tech
Early Access to eBooks as they are being written
Personalised content suggestions
Customised display settings for better reading experience
50+ new titles added every month on new and emerging tech
Playlists, Notes and Bookmarks to easily manage your learning
Mobile App with offline access
What do you get with eBook?
Download this book in EPUB and PDF formats
Access this title in our online reader
DRM FREE - Read whenever, wherever and however you want
Online reader with customised display settings for better reading experience
What do you get with video?
Download this video in MP4 format
Access this title in our online reader
DRM FREE - Watch whenever, wherever and however you want
Online reader with customised display settings for better learning experience
What do you get with video?
Stream this video
Access this title in our online reader
DRM FREE - Watch whenever, wherever and however you want
Online reader with customised display settings for better learning experience
What do you get with Audiobook?
Download a zip folder consisting of audio files (in MP3 Format) along with supplementary PDF
What do you get with Exam Trainer?
Flashcards, Mock exams, Exam Tips, Practice Questions
Access these resources with our interactive certification platform
Mobile compatible-Practice whenever, wherever, however you want
BUY NOW $10 p/m for first 3 months. $15.99 p/m after that. Cancel Anytime!
Subscription
What do you get with a Packt Subscription?
This book & 7000+ ebooks & video courses on 1000+ technologies
60+ curated reading lists for various learning paths
50+ new titles added every month on new and emerging tech
Early Access to eBooks as they are being written
Personalised content suggestions
Customised display settings for better reading experience
50+ new titles added every month on new and emerging tech
Playlists, Notes and Bookmarks to easily manage your learning
Mobile App with offline access
What do you get with a Packt Subscription?
This book & 6500+ ebooks & video courses on 1000+ technologies
60+ curated reading lists for various learning paths
50+ new titles added every month on new and emerging tech
Early Access to eBooks as they are being written
Personalised content suggestions
Customised display settings for better reading experience
50+ new titles added every month on new and emerging tech
Playlists, Notes and Bookmarks to easily manage your learning
Mobile App with offline access
What do you get with eBook + Subscription?
Download this book in EPUB and PDF formats, plus a monthly download credit
This book & 6500+ ebooks & video courses on 1000+ technologies
60+ curated reading lists for various learning paths
50+ new titles added every month on new and emerging tech
Early Access to eBooks as they are being written
Personalised content suggestions
Customised display settings for better reading experience
50+ new titles added every month on new and emerging tech
Playlists, Notes and Bookmarks to easily manage your learning
Mobile App with offline access
What do you get with a Packt Subscription?
This book & 6500+ ebooks & video courses on 1000+ technologies
60+ curated reading lists for various learning paths
50+ new titles added every month on new and emerging tech
Early Access to eBooks as they are being written
Personalised content suggestions
Customised display settings for better reading experience
50+ new titles added every month on new and emerging tech
Playlists, Notes and Bookmarks to easily manage your learning
Mobile App with offline access
What do you get with eBook?
Download this book in EPUB and PDF formats
Access this title in our online reader
DRM FREE - Read whenever, wherever and however you want
Online reader with customised display settings for better reading experience
What do you get with video?
Download this video in MP4 format
Access this title in our online reader
DRM FREE - Watch whenever, wherever and however you want
Online reader with customised display settings for better learning experience
What do you get with video?
Stream this video
Access this title in our online reader
DRM FREE - Watch whenever, wherever and however you want
Online reader with customised display settings for better learning experience
What do you get with Audiobook?
Download a zip folder consisting of audio files (in MP3 Format) along with supplementary PDF
What do you get with Exam Trainer?
Flashcards, Mock exams, Exam Tips, Practice Questions
Access these resources with our interactive certification platform
Mobile compatible-Practice whenever, wherever, however you want
  1. Free Chapter
    Getting Started with OpenLayers
About this book

This book is a practical, hands-on guide that provides you with all the information you need to get started with mapping using the OpenLayers 3 library.

The book starts off by showing you how to create a simple map. Through the course of the book, we will review each component needed to make a map in OpenLayers 3, and you will end up with a full-fledged web map application. You will learn the key role of each OpenLayers 3 component in making a map, and important mapping principles such as projections and layers. You will create your own data files and connect to backend servers for mapping. A key part of this book will also be dedicated to building a mapping application for mobile devices and its specific components.

Publication date:
January 2015
Publisher
Packt
Pages
512
ISBN
9781782162360

 

Chapter 1. Getting Started with OpenLayers

Within the past few years, the popularity of interactive web maps has exploded. In the past, creating interactive maps was reserved for large companies or experts with lots of money. But now, with the advent of free services such as Google and Bing Maps, online mapping is easily accessible to everyone. Today, with the right tools, anyone can easily create a web map with little or even no knowledge of geography, cartography, or programming.

Web maps are expected to be fast, accurate, and easy to use. Since they are online, they are expected to be accessible from anywhere on nearly any platform. There are only a few tools that fulfill all these expectations. OpenLayers is one such tool. It's free, open source, and very powerful. Providing both novice developers and seasoned GIS professionals with a robust library, OpenLayers makes it easy to create modern, fast, and interactive web-mapping applications for desktop and mobile.

In this chapter, we will:

  • Learn in detail about OpenLayers

  • Discuss some web mapping application concepts

  • Make our first map

  • Provide information on resources

 

Introducing OpenLayers


OpenLayers is an open source, client-side JavaScript library for making interactive web maps, viewable in nearly any web browser. Since it is a client-side library, it requires no special server-side software or settings—you can use it without even downloading anything! Originally developed by MetaCarta as a response, in part, to Google Maps, the 2.x series of the library has grown into a mature, popular framework with many passionate developers and a very helpful community. At the time of writing, this version is still actively used and maintained, but this book will focus on the latest version, which is 3.0. For people wishing to switch to OpenLayers 3, particularly people already using the OpenLayers 2 series, the main reasons to change are:

  • OpenLayers 2 was released eight years back, and it has its design flaws. As the first main open source mapping library, its conception has been done along the way with web evolution, particularly with JavaScript. Due to these facts, code modularity suffered and it was becoming impossible to make new evolutions.

  • OpenLayers 3 provides out-of-the-box mobile support.

  • The library ability to easily incorporate animation.

  • The Canvas renderer by default, which is more efficient than the DOM renderer bundled in OpenLayers 2.x, and the WebGL support in the roadmap, enabling a more powerful map display than Canvas.

  • Increased performance and build size using Closure Compiler.

  • The maintenance mode on OpenLayers 2 series that will limit your application for future usages.

You can also add the fact that the library is already used in production, that demonstrates good performance at the Swiss federal geoportal, http://map.geo.admin.ch (see screenshot for reference ) and the OpenGeo Suite, a commercial open source based solution which already bundles the library:

 

Advantages of using OpenLayers


OpenLayers makes creating powerful web mapping applications easy and fun. It is very simple to use—you don't even need to be a programmer to make a great map with it. It's open source, free, and has a strong community behind it. A big advantage of OpenLayers is that you can integrate it into any closed or open source application because it is released under the BSD 2-Clause license. So, if you want to dig into the internal code, or even improve it, you're encouraged to do so. Cross browser compatibility is handled for you by the Google Closure Library— but you need to have IE9+ because VML rendering (specific to IE8 and older versions) is no longer supported. Furthermore, OpenLayers 3.0 supports modern mobile, touch devices making it easy to develop for mobile technology.

OpenLayers is not tied to any proprietary technology or company, so you don't have to worry much about your application breaking with third party code (unless you break it). Although it's open source, you will get good support from the community and there are commercial support options as well. The library is recognized as well —established by the OSGeo (Open Source Geospatial Foundation), having passed through the OSGeo Incubation process, a kind of open source quality mark for geospatial projects.

Note

You can read further about OSGeo Incubation at http://wiki.osgeo.org/wiki/Incubation_Committee

OpenLayers allows you to build entire mapping applications from the ground up, with the ability to customize every aspect of your map—layers, controls, events, and so on. You can use a multitude of different map server backends together, including a powerful vector layer. It makes creating map mashups extremely easy.

 

What, technically, is OpenLayers?


We said OpenLayers is a client-side JavaScript library, but what does this mean? The following context answers this question.

Client side

When we say client-side, we are referring to the user's computer, specifically their web browser. The only thing you need to make OpenLayers work is the OpenLayers code itself and a web browser. You can either download it and use it on your computer locally, or download nothing and simply link to the JavaScript file served on the site that hosts the OpenLayers project (http://openlayers.org). OpenLayers works on nearly all modern web browsers and can be served by any web server or your own computer. Using a modern, standard based browser such as Firefox, Google Chrome, Safari, or Opera is recommended.

Library

When we say library, we mean that OpenLayers is a map engine that provides an API (Application Program Interface) that can be used to develop your own web maps. Instead of building a mapping application from scratch, you can use OpenLayers for the mapping part, which is maintained and developed by a bunch of brilliant people.

For example, if you'd want to write a blog, you could either write your own blog engine, or use an existing one such as WordPress or Drupal and build on top of it. Similarly, if you'd want to create a web map, you could either write your own from scratch, or use software that has been developed and tested by a group of developers with a strong community behind it.

By choosing to use OpenLayers, you do have to learn how to use the library (or else you wouldn't be reading this book), but the benefits greatly outweigh the costs. You get to use a rich, highly tested, and maintained code base, and all you have to do is learn how to use it. Hopefully, this book will help you with it.

OpenLayers is written in JavaScript, but don't fret if you don't know it very well. All you really need is some knowledge of the basic syntax, and we'll try to keep things as clear as possible in the code examples.

Note

If you are unfamiliar with JavaScript, Mozilla provides phenomenal JavaScript documentation at https://developer.mozilla.org/en/javascript. We should also visit Eloquent JavaScript at http://eloquentjavascript.net, an online book to get started with the JavaScript language We recommend you also do some interactive exercises at Codecademy, http://codecademy.com, a website dedicated to learn JavaScript programming basics and much more.

 

Anatomy of a web mapping application


First off, what is a web-mapping application? To put it bluntly, it's some type of Internet application that makes use of a map. This could be a site that displays the latest geo-tagged images from Flickr (we'll do this in Chapter 11, Creating Web Map Apps), a map that shows markers of locations you've traveled to, or an application that tracks invasive plant species and displays them. If it contains a map and it does something, you could argue that it is a web map application. The term can be used in a pretty broad sense.

So, where exactly does OpenLayers fit in? We know OpenLayers is a client-side mapping library, but what does that mean? Let's take a look at the following figure:

This is called the client/server model and it is, essentially, the core of how all web applications operate. In the case of a web map application, some sort of map client (for example: OpenLayers) communicates with some sort of web map server (for example: a map server using the WMS (Web Map Service) standard, an OpenStreetMap backend, or some satellite images). We've added a bit of complexity in it because the truth is that you can also rely only on client-side for web mapping applications using static content that you have pre-generated. To illustrate, you can use GeoJSON files, a JSON based format to display pins. For example, it is very useful for mobile content.

Web map client

OpenLayers lives on the client-side. One of the primary tasks the client performs is to get map images from a map server. Essentially, the client asks a map server for what you want to look at. Every time you navigate or zoom around on the map, the client has to make new requests to the server—because you're asking to look at something different.

OpenLayers handles this all for you, and it is happening via AJAX (asynchronous JavaScript + XML) calls to a map server. Refer to http://en.wikipedia.org/wiki/Ajax_(programming) for further information on AJAX. To reiterate—the basic concept is that OpenLayers sends requests to a map server for map data every time you interact with the map, then OpenLayers pieces together all the returned map data (which might be images or vector data) so it looks like one big, seamless map. In Chapter 2, Key Concepts in OpenLayers, we'll cover this concept in more depth.

Web map server

A map server (or map service) provides the map itself. There are a myriad of different map server backends. The examples include:

  • The map servers using WMS and WFS standards (such as the GeoServer, Mapserver, and so on)

  • Proprietary backends provided such as Bing Maps or Esri's ArcGIS Online, mainly based on proprietary data

  • Backends based on OpenStreetMap data such as the official OpenStreetMap, Stamen maps, or MapQuest maps

If you are unfamiliar with these terms, don't sweat it. The basic principle behind all these services is that they allow you to specify the area of the map you want to look at (by sending a request), and then the map servers send back a response containing the map image. With OpenLayers, you can choose to use as many different backends in any sort of combination as you'd like.

Note

OpenLayers is not a web map server; it only consumes data from them. So, you will need access to some type of WMS. Don't worry about it though. Fortunately, there are a myriad of free and/or open source web map servers available that are remotely hosted or easy to set up yourself, such as MapServer. We speak a lot about web map servers but you must be aware that depending on your web-mapping application, you can use geographic data files to provide the needed data consumed by OpenLayers.

Throughout this book, we'll often use a freely available web-mapping service from http://www.openstreetmap.org/, so don't worry now about having to provide your own.

With many web map servers, you do not have to do anything to use them—just supplying a URL to them in OpenLayers is enough. OSGeo, OpenStreetMap, Google, Here Maps, and Bing Maps, for instance, provide access to their map servers (although some commercial restrictions may apply with various services in some situations).

 

Connecting to Google, Bing Maps, and other mapping APIs


The Google, Yahoo!, Bing, and ESRI's Mapping APIs allow you to connect with their map server backend. Their APIs also usually provide a client-side interface.

The Google Maps API, for instance, is fairly powerful. You have the ability to add markers, plot routes, and use KML data (things you can also do in OpenLayers)—but the main drawback is that your mapping application relies totally on Google. The map client and map server are provided by a third party. This is not inherently a bad thing, and for many projects, Google Maps and the others like it, are a good fit.

However, there are quite a few drawbacks such as:

  • You're not in control of the backend

  • You can't really customize the map server backend, and it can change any time

  • There may be commercial restrictions, or some costs involved for consuming maps images or other services such as geocoding or routing for car traffic

  • These other APIs also cannot provide you with anything near the amount of flexibility and customization that an open source mapping application framework (that is, OpenLayers) offers

    Note

    Although we mentioned Google Maps API as one of the main maps, its support in OpenLayers is limited. As there are more tiles providers nowadays, it's not worth it to have code maintenance to support Google Maps API, a third party code that can break the main library, as sometimes happened earlier with the OpenLayers 2 API.

Layers in OpenLayers

So, what's with the layers in OpenLayers? Well, OpenLayers allows you to have multiple different backend servers that your map can use. To access a web map server, you declare a layer and add it to your map with OpenLayers.

For instance, if you wanted to have a Bing Maps and an OpenStreetMap service displayed on your map, you would use OpenLayers to create a layer referencing Bing Maps and another one for OpenStreetMap, and then add them to your OpenLayers map. We'll soon see an example with an OpenStreetMap layer, so don't worry if you're a little confused.

Understanding a layer

Like layers of an onion, each layer is above and will cover up the previous one; the order that you add in the layers is important. With OpenLayers, you can arbitrarily set the overall transparency of any layer, so you are easily able to control how many layers cover each other up, and dynamically change the layer order at any time.

Most of the time, you make a distinction between base layers and non-base layers. Base layers are layers below the others and are used as a background on your maps to give general context. When you choose one base layer, the others will not be shown. On the top of base layers, you have non-base layers used to emphasize particular topics. You can also choose to use only overlay layers if you're considering that they are enough to understand the map. As a classical example, you could have a Bing map as your base layer, a layer with satellite imagery that is semi-transparent, and a vector layer, all active on your map at once. A vector layer is a powerful layer that allows for the addition of markers and various geometric objects to our maps—we'll cover it in Chapter 5, Using Vector Layers. Thus, in this example, your map would have three separate layers. We'll study in detail about layers and how to use and combine them in Chapter 4, Interacting with Raster Data Source.

Note

At the code level, the distinction between base and non-base layers can be misleading. It does not exist in OpenLayers 3, whereas it was in OpenLayers 2 series. However, the concept remains interesting to conceive your maps.

The OpenLayers website

The website for OpenLayers 3 is located at http://openlayers.org. Have a look at the following screenshot:

To begin, you need to download a copy of OpenLayers (or we can directly link to the library—but we'll download a local copy). You can download the compressed library as a .zip by clicking on the green button at the bottom of the release page at https://github.com/openlayers/ol3/releases/tag/v3.0.0.

We will cover the website links by following the different areas of the main web page. Let's start with the navigation bar located at the top right area:

  • First link, Learn refers to the documentation for the OpenLayers library.

  • Examples points to the list of the latest examples available for the current development library. At the time of writing, you can see 95 of them. You can filter the list of examples with keywords to find your way.

  • API redirects to the API documentation. It documents the API where you can find the syntax, methods, and properties for all the core library components. Without it, it would be impossible to find your way within the library.

  • Last link, Code is simply the link to the Github library account located at http://github.com/openlayers/ol3, for people who want to contribute or learn more about the core library code.

  • In the central area, the main content is divided from top to bottom in four parts:

  • The first block LATEST speaks for itself. It's the latest news about the project.

  • The FEATURES part is a good reminder and teaser about what you can do with the OpenLayers library.

  • The LEARN MORE part is one of the most important parts of the web page:

    • With Quick Start, you can learn a simple way to make your first map.

    • The Download section is the place to find all release codes hosted at GitHub. You can also find the releases notes — the list of evolution and fixes to the library core code.

    • The Tutorials section is the entry to learn more after the Quick Start. At the time of writing, it's nearly empty. It should grow following the library adoption curve.

    • The API Docs section is one of the keys of OpenLayers. It documents the API where you can find the syntax, methods, and properties for all the core library components. Without it, it would be impossible to find your way within the library.

  • GET INVOLVED, the last block, is also important when you want to find help or make a contribution:

    • Fork the repo sends you to the URL of the official development repository on Github.

    • Open a ticket is the place where you can create a ticket. You can do it to describe an unexpected behavior when using the library, or if you want to ask for a new feature in the library, or if you are an advanced user or a developer and wish to submit code or give your opinion on an existing ticket.

    • The last topic Join the discussion links to the official OpenLayers 3 mailing list.

      Tip

      Be aware that currently both versions of OpenLayers exist

 

Time for action – downloading OpenLayers


Let's download the OpenLayers library. After you're done, you should have the OpenLayers library files set up on your computer. Perform the following steps:

  1. Go to the OpenLayers website (http://openlayers.org), go to the Download part to follow the link and download the v3.0.0.zip version of the OpenLayers v3.0.0. It's the green button on the bottom left of the Github release page for v3.0.0.

  2. Extract the file you just downloaded. When you extract it, you'll end up with a folder called v3.0.0 (or whatever your version is).

  3. Open the v3.0.0 folder. Once inside, you'll see a lot of folders, but the ones we are concerned with right now are the folders named build and css, as seen in the following screenshot:

  4. Create an ol3 folder within an assets folder contained within a new folder ol3_samples in your home directory (or C:\ on Windows). Copy the previous build folder from v3.0.0 and rename it as js into the new ol3 directory and also copy the css folder into the same ol3 folder.

  5. Create a new folder called sandbox into the ol3_samples directory. You can name the folder whatever you like, but we'll refer to it as the sandbox folder. Your new folder structure should look similar to the following screenshot:

What just happened?

We just installed OpenLayers 3 by copying over different pre-built, compressed JavaScript files containing the entire OpenLayers 3 library code (from the build directory) and the associated assets (style sheets). To use OpenLayers, you'll need at a minimum, the ol.js file (the other .js files will be needed during the book but are not always required) and the ol.css file. For best practice, we already gave you some tips to structure the code like separate assets, such as css and js, or separate library code from your own code.

If you open the ol.js file, you'll notice it is nearly unreadable. This is because this is a minified and obfuscated version, which basically means extra white space and unnecessary characters have been stripped out to cut down on the file size and some variables have been shortened whenever possible. While it is no longer readable, it is a bit smaller and thus requires less time to download. If you want to look at the uncompressed source code, you can view it by looking in the ol-debug.js file within the js folder of the ol3 directory.

You can, as we'll see in the last chapter of this book, build your own custom configurations of the library, including only the things you need. But for now, we'll just use the entire library. Now that we have our OpenLayers library files ready to use, let's make use of them!

Making our first map

The process for creating a map with OpenLayers requires, at a minimum, the following things:

  • Include the OpenLayers library files

  • Creating an HTML element that the map will appear in

  • Creating a layer object from a ol.layer.* class

  • Creating a map object from the ol.Map class by adding a layer

  • Creating a view from the ol.View class to set for the Map class (defining the area where the map will initially be displayed)

Now, we're finally ready to create our first map!

 

Time for action – creating your first map


Let's dive into OpenLayers and make a map! After you finish this section, you should have a working map, which uses a publicly available OSM server backend from the OpenStreetMap.org project. Execute the following steps:

  1. Navigate to the assets directory, create a folder css, and create a new file called samples.css. Add the following code:

    map {
      height: 500px;
      width: 100%;
      background-color: #b5d0d0;
    }
  2. Add the following code to a new file called hello_openstreetmap.html and save the file in the sandbox directory. If you are using Windows, we suggest using Notepad++ in particular because you need to be sure you're editing UTF-8 encoded files. On Linux, you can use Gedit or Geany and for Mac OSX, you can use Text Wrangler (free but not open source). Do not try to edit the file in a program such as Microsoft Word, as it will not save properly. The following code will also be used as the base template code for many future examples in this book, so we'll be using it often and coming back to it a lot:

    <!doctype html>
      <head>
        <title> Hello OpenStreetMap </title>
        <link rel="stylesheet" href="../assets/ol3/css/ol.css" type="text/css" />
        <link rel="stylesheet" href="../assets/css/samples.css" type="text/css" />
      </head>
      <body>
        <div id="map" class="map"></div>
    <script src="../assets/ol3/js/ol.js">
    </script>
    <script>
            var osmLayer = new ol.layer.Tile({
              source: new ol.source.OSM()
            });
           var birmingham = ol.proj.transform([-1.81185, 52.44314], 'EPSG:4326', 'EPSG:3857');
           var view = new ol.View({
              center: birmingham,
              zoom: 6
            });
            var map = new ol.Map({
              target: 'map'
            });
            map.addLayer(osmLayer);
            map.setView(view);
        </script>
      </body>
    </html>
  3. Open hello_openstreetmap.html in your web browser. It can be hosted on a server or opened as a file. You should see something similar to the screenshot that follows:

What just happened?

We just created our first map using OpenLayers! If it did not work for you for some reason, try double-checking the code and making sure all the commas and parentheses are in place. You can also open the browser debugger and look for JavaScript errors within the console. If you don't know what a console is, don't worry, we will see it soon. You can also refer to the Preface where a link to code samples used in the book is given. By default, we're given a few controls if we don't specify any. We will use the file we created as a template for many examples throughout the book, so save a copy of it so you can easily refer to it later.

The control on the left side (the navigation buttons) is called the Zoom control, which is a ol.control.Zoom object. You can click the buttons to navigate around the map, drag the map with your mouse, use the scroll wheel to zoom in, or use your keyboard's arrow keys. ol.control.Attribution is added by default. It will be populated if a layer (such as OSM) has attribution info available. This control is on the bottom right corner and gives the credits for the data you're using such as license and data producer.

We'll cover controls in greater detail in Chapter 9, Taking Control of Controls.

Now, let's take a look at the code, line by line.

  • Lines 1 to 7: It sets up the HTML page. Every HTML page needs an <html> and <head> tag, and the extraneous code you see specifies various settings that inform your browser that this is an HTML5 compliant page. For example, we include the DOCTYPE declaration in line 1 to specify that the page conforms to standards set by the WC3. We also specify a <title> tag, which contains the title that will be displayed on the page. We also add a css stylesheet content to display correctly the zoom and attribution controls, and set the future map size to a height of 500px and a width of 100% (the width will always be at the max width depending on the browser window).

    This is the structure that all our code examples will follow, so this basic code template will be implicitly assumed in all examples that follow throughout the book.

  • Lines 8 and 9:

    <body>
    <div id="map" class="map"></div>

    To make an OpenLayers map, we need an HTML element where the map will be displayed in. Almost always, this element will be a div. You can give it whatever ID you would like, and the ID of this HTML element is passed into the call to create the map object. You can style the <div> tag however you would like—setting the width and height to be 100 percent, for instance, if you want a full page map. We choose a class for this, also called map.

  • Line 10:

    <script src="../assets/ol3/js/ol.js" type="text/javascript"></script>

    This includes the OpenLayers library. The location of the file is specified by the src='../assets/ol3/js/ol.js' attribute. Here, we're using a relative path. As the hello_openstreetmap.html page is within the sandbox at the same level as the assets, we need to go outside the sandbox directory and then set the path to ol.js file . The file could either be on your computer, or another computer. Browsers can load it on any computer thanks to the relative path.

    We can also use an absolute path, which means we pass in a URL where the script is located at. openlayers.org hosts the script file as well; we could use the following line of code to link to the library file directly:

    <script src='http://openlayers.org/en/v3.0.0/build/ol.js></script>

    Notice how the src specifies an actual URL which is an absolute path http://openlayers.org/en/v3.0.0/css/ol.css at line 5. Either way works, however, throughout the book we'll assume that you are using a relative path and have the OpenLayers library on your own computer/server. If you use the hosted OpenLayers library, you cannot be sure that it will always be available, so using a local copy is recommended.

    Be aware that when browsers load a page, they load it from top to bottom. To use any DOM (Document Object Model) elements (any HTML element on your page) in JavaScript, they first have to be loaded by the browser. So, you cannot reference HTML with JavaScript before the browser sees the element. It'd be similar to trying to access a variable that hasn't yet been created. Because of this behavior, don't forget to call your JavaScript content after the <div id="map" class="map"></div>.

  • Line 11: This starts a <script> block. We'll set up all our code inside it to create our map. Since the OpenLayers library has been included in line 13, we are able to use all the classes and functions the library contains.

  • Lines 12 to 14:

      var osmLayer = new ol.layer.Tile({
      source: new ol.source.OSM()
    });

    In the previous three lines of code, we created a global variable called osmLayer. In JavaScript, any time we create a variable we need to place var in front of it to ensure that we don't run into scope issues (what functions can access which variables). When accessing a variable, you do not need to put var in front of it.

    Since we are defining osmLayer as a variable at the global level (outside of any functions), we can access it anywhere in our code. We declare the osmLayer as an ol.layer.Tile object. It means we use an ol.layer.Tile class for creating the variable layerOsm.

    The object created is also referred to as an instance of the ol.layer.Tile class. We'll talk about what this means later in the Appendix A, Object-oriented Programming – Introduction and Concepts.

    Now, let's look at the right hand side of the equal sign (=): new keyword means that we are creating a new object from the class that follows it. ol.layer.Tile is the class name which we are creating an object from. Notice that something is inside the parenthesis: {source: new ol.source.OSM()}. This means we are passing one thing into the class (called an argument). Every class in OpenLayers expects different arguments to be passed into it, and some classes don't expect anything.

    The ol.layer.Tile class expects one parameter following the API doc reference. Take a look at: http://openlayers.org/en/v3.0.0/apidoc/ol.layer.Tile.html. The {source: new ol.source.OSM()} is the layer options, consisting of key:value pairs (for example, {key:value} ). This is also called JavaScript Object Literal Notation, a way to create objects on the fly.

    Tip

    JavaScript object literal notation

    In OpenLayers, we often pass in anonymous objects to classes . In JavaScript, anonymous objects are commas separated key:value pairs, and are set up in the format of {key1:value1, key2:value2}. They are, basically, objects that are created without deriving from a class. This format is also referred to as object literal notation.

    When we say key1:value1, it's similar to saying key1 = value1, but we use a colon instead of an equals sign. We can also affect to a variable an object and reuse this variable instead of creating it on the line, for example:

    var layer_parameters = {source: new ol.source.OSM()};
    var osmLayer = new ol.layer.Tile(layer_parameters);

    So, the option source new ol.source.OSM() is the way to tell the characteristic of the tiles we want to retrieve such as the URL or the default attribution text, whereas ol.layer.Tile is the way to say how you ask the map image, not where it comes from.

    The type of ol.source can be any from a multitude of different services, but we are using OSM here as a source. OSM (OpenStreetMap), is a crowdsourcing project focusing on creating open source map data. The main visible part of the project is the OSM world map we are using.

    The arguments, like the source we can pass in for layers, are dependent on the layer class—we cover layers in detail in Chapter 3, Charting the Map Class. If you don't want to wait, you can also check out the documentation at http://openlayers.org/en/v3.0.0/apidoc/ to see what arguments different layers of classes expect.

  • Line 15:

    var birmingham = ol.proj.transform([-1.81185 52.44314], 'EPSG:4326', 'EPSG:3857');

    In this line of code, we take coordinates from a place, Birmingham in the UK, and we use a custom function that transforms [longitude, latitude] to the projected coordinate the map will expect in the view.

  • Lines 16 to 19:

    var view = new ol.View({ center: birmingham zoom: 6 });

    In the preceding four lines of code, we are defining a view from class ol.View. It's to use a view. Until now, we have defined what we will see, but with the view, we will define from where we are seeing it. Think of view as equivalent to a shot you might see in a cinema and where the cameraman chooses to see actors with more or less light, from far away or near, from below or above. Maps are usually 2D objects but because of new capabilities in the library, you can also have a tilted 2D view. We will not cover it because it requires advanced knowledge.

    We have two options here in the JavaScript object: center and zoom.

    The first one sets the center of the map with coordinates. These are not using latitude and longitude coordinates but Spherical Mercator coordinates, a common web mapping standard projection. We will explain this topic in Chapter 7, Wrapping Our Heads Around Projections.

    The zoom is a way to set the level of details you get on the map when you open the web page. Change this value to understand better. The value for using the OSM layer can be between 0 and 18. The more you increase the value, the more you zoom in. If you set the value to 20, you will see that the image is always of the level 18 but the library resizes the image itself and and the image quality will be reduced.

    Note

    Since this is the last thing passed into the ol.View object creation call, make sure there is not a trailing comma. Trailing commas are a common error and are often tedious to debug.

  • Lines 20 to 22:

    var map = new ol.Map({ target: 'map' });

    We previously created a layer in order to add it to a map but this map was not already created. We have done it using the ol.Map class. The map object is the crux of our OpenLayers application— we call its functions to tell the view bound to the map to zoom to areas, fire off events, keep track of layers, and so on.

    The ol.Map class expects a JavaScript object parameter. Within this object, we use one object parameter: target. You can provide another parameter renderer to choose the way the image will be displayed in the browser. It can be, DOM, Canvas, or WebGL. Don't worry about these terms, we will explain what they cover. This is not a mandatory option but we'd prefer to tell you already to be aware of this. You will learn more about this in Chapter 2, Key Concepts in OpenLayers.

    The other object parameter is target. Its purpose is to set where you will attach your map in the HTML. It refers to the id of an HTML element available in your web page.

    Notice, we don't include everything on one line when creating our map object—this improves readability, making it easier to see what we pass in. The only difference is that we are also adding a new line after the comma separating arguments, which doesn't affect the code (but does make it easier to read).

  • Line 23:

    map.addLayer(osmLayer);

    Now that we have created both the map and layer, we can add the layer to the map. In OpenLayers, every map needs to have at least one layer. The layer points to the backend, or the server side map server, as we discussed earlier.

    Notice, we are calling a function of the map object. There are actually a few ways to go about adding a layer to a map object. We can use the previous code (by calling map.addLayer), where we pass in an individual layer but we can also add the layers when instantiating the ol.Map with something such as the following:

    var map = new ol.Map({ target: 'map',
      layers: [osmLayer]
    });

    In this second case, you have to create your layer before the map. Most official examples use the second syntax but for learning purposes, we thought it would be better to separate map instantiation from layers addition.

  • Line 24:

    map.setView(view);

    This line enables you to set the view to render the image and display it at the right place you defined previously in the ol.View instance, the view variable.

  • Lines 25 to 27:

        </script>
      </body>
    </html>

    These lines close the JavaScript block and the remaining HTML blocks.

    After reviewing this first example, if the concept of object-oriented programming is unfamiliar to you, we recommend that you take some time to explore this topic. While you don't necessarily need to know OOP concepts thoroughly to use this book, understanding keywords such as class, properties, abstract class, methods, instance, constructor, or inheritance should ring a bell in your mind. If not, we advise you to visit the Appendix A, Object-oriented Programming – Introduction and Concepts.

    Now, let's introduce you to the main resources for getting the most important information about OpenLayers and its ecosystem.

 

Where to go for help


Our coverage of the sample code was not meant to be extremely thorough; just enough to give you an idea of how it works. We'll be covering OOP concepts in more detail throughout the remaining chapters, so if anything is a bit unclear, don't worry too much.

As OpenLayers is a library and provides functions for you, it is important to know what these functions are and what they do. There are many places to do this, but the best source is the API docs.

API docs

The API documentation is always up-to-date and contains an exhaustive description of all the classes in OpenLayers. It is usually the best and first place to go when you have a question. You can access the documentation at: http://openlayers.org/en/v3.0.0/apidoc/ for the 3.0.0 release. It contains a wealth of information. We will constantly refer to it throughout the book, so keep the link handy! Sometimes, however, the API docs may not seem clear enough, but there are plenty of other resources out there to help you. We'll cover a bit about how to find your way in API documentation in Chapter 2, Key Concepts in OpenLayers and in Appendix A, Object-oriented Programming – Introduction and Concepts.

This book's website

The extension website for this book can be found at: http://openlayersbook.github.io/openlayersbook/. Current, up-to-date corrections and code fixes, along with more advanced tutorials and explanations, can be found there. You can also grab the code and more information about this book at Packt Publishing's website, located at https://www.packtpub.com/web-development/openlayers-3-beginner%E2%80%99s-guide.

Mailing lists

The OpenLayers mailing list is an invaluable resource that lets you not only post questions, but also browse questions others have asked (and answered). There were two main OpenLayers news groups—Users and Dev for the OpenLayers 2 Version. There is a list only for OpenLayers 3 development discussions located at https://groups.google.com/forum/#!forum/ol3-dev. You may find some users' questions in the archives as it was before for both development and users questions.

Now, user questions should be only posted on http://stackoverflow.com and tagged with openlayers. OpenLayers 3 library developers will answer directly here.

When posting a question, please be as thorough as possible, stating your problem, what you have done, and the relevant source code (for example, "I have a problem with using a WMS layer. I have tried this and that, and here is what my source code looks like..."). A good guideline for asking questions in a way that will best elicit a response can be found at http://www.catb.org/~esr/faqs/smart-questions.html.

Other online resources

Books are great, but they're basically just a one way form of communication. If you have any questions that the book does not answer, your favorite search engine is the best place to go to. The Questions and Answers website http://gis.stackexchange.com, the young brother of StackOverflow, dedicated to GIS (Geographical Information System) can also be quite useful. But, at the end, don't forget that mailing lists and IRC are other great resources.

 

OpenLayers issues


Sometimes, you will hit an error without understanding why you encounter it, for example related to a mobile browser's unexpected behavior. Before asking to check mailing lists or IRC, we encourage you to make a small search in the list of issues located at Github https://github.com/openlayers/ol3/issues. You can search issues by milestone, status (opened, closed, etc), or keywords.

IRC

IRC (Internet Relay Chat) is another great place to go to if you have questions about OpenLayers. IRC is used for group communication; a big chat room, essentially. If you have exhausted Google, issues' trackers, and the mailing list, IRC provides you in real time with other people interested in OpenLayers.

Generally, the people who hang out in the OpenLayers chat room are very friendly, but please try to find an answer before asking in IRC. The server is irc.freenode.net and the chat room is #openlayers. You can download an IRC client online; a good Windows one is mIRC (http://mirc.com). More information about how to use IRC can be found at http://www.mirc.com/install.html. For beginners, we recommend using Chatzilla, a Firefox Mozilla add—on http://chatzilla.hacksrus.com or CIRC, a Google Chrome add—on http://flackr.github.io/circ/.

When you've installed it, just type irc://irc.freenode.net/openlayers (for Chatzilla only) in your browser address bar, press enter, wait and you're ready to speak on OpenLayers IRC channel.

 

OpenLayers source code repository


The source code repository location is hosted at GitHub. You can access the entire code repository at http://github.com/openlayers/ol3.

Feel free to download a copy and play around with it yourself. When you become an advanced user, you can submit evolutions to the official source code base and become a contributor to the library. Without going so far, it cannot hurt to download a copy of the code base and look around it yourself to figure out how it's really working!

 

Getting live news from RSS and social networks


Nowadays, some people prefer to aggregate content using RSS feeds or social networks.

Let's review how you can access alternatively to all the previous resources and more.

For the OpenLayers 3 Developers mailing list, you can use atom or RSS feed, available at https://groups.google.com/forum/#!aboutgroup/ol3-dev

When you want to get news about OpenLayers 3 development, you have to rely on Github website capabilities.

You can see:

 

Summary


In this chapter, we were introduced to OpenLayers and learnt a bit about it.

We saw what web map applications are and how they work. After that, we created our first map with OpenLayers, then analyzed how the code works. Then, we covered a fundamental concept, object-oriented programming, which we'll need to know about while really working with OpenLayers. Lastly, resources for help and information outside this book were provided.

Now that we have a basic handle on OpenLayers, we'll jump straight into Chapter 2, Key Concepts in OpenLayers. We will discover relationships between library core parts. Using examples, we will also review Events and Observe behaviors. It would be impossible to get an interactive map without them. Then, to finish, we will focus on basic debugging techniques. To learn more about JavaScript debugging, you can also refer to Appendix C, Squashing Bugs with Web Debuggers.

About the Authors
  • Thomas Gratier

    Thomas Gratier is a GIS consultant who provides web development, consulting, and training services in Nantes, France. He is an open source advocate and a charter member of The Open Source Geospatial Foundation (OSGeo) (http://www.osgeo.org). He gets involved in writing French translations for open source geospatial projects, such as MapServer and Zoo Project. With like-minded professionals, he contributes to the weekly geospatial news updates at Geotribu (http://geotribu.net). With an MSc degree in geography and urban planning from The Institute Of Alpine Geography at Grenoble University, his career spanning 8 years steered more towards technical programming work, but he always kept his geospatial passion in mind. He has worked for public authorities on water and flood risk prevention and management, various private consultancies in urban planning developing web mapping solutions, and multinational company CapGemini's GIS Division in France. More information can be found on his website at Web Geo Data Vore (http://webgeodatavore.com).

    Browse publications by this author
  • Paul Spencer

    Paul Spencer is a software engineer who has worked in the field of open source geospatial software for more than 15 years. He is a strong advocate of open source development and champions its use whenever possible. Paul has architected several successful open source projects and been actively involved in many more. Paul was involved in the early design and development of OpenLayers and continues to be involved as the project evolves. Paul joined DM Solutions Group (DMSG) in 1998, bringing with him advanced software development skills and a strong understanding of the software-development process. In his time with the company, Paul has taken on a leadership role as the CTO and primary architect for DM Solutions Group's web mapping technologies and commercial solutions. Prior to joining DMSG, Paul worked for the Canadian Military, after achieving his master's degree in software engineering from The Royal Military College of Canada.

    Browse publications by this author
  • Erik Hazzard

    Erik Hazzard is the author of OpenLayers 2.10 Beginner's Guide, Packt Publishing. He has worked as the lead developer for a GIS-based company, has done contracting work with the design studio, Stamen, and has co-founded two start-ups. Erik is passionate about mapping, game development, and data visualization. In his free time, he enjoys writing and teaching, and can be found at http://vasir.net.

    Browse publications by this author
Latest Reviews (5 reviews total)
comprehensive guide, good read
OpenLayers 3: Beginner's Guide
Unlock this book and the full library FREE for 7 days
Start now