Home Data OpenLayers 3.x Cookbook - Second Edition

OpenLayers 3.x Cookbook - Second Edition

By Peter J. Langley , Antonio Santiago Perez
books-svg-icon Book
Subscription FREE
eBook + Subscription $12.99
eBook $39.99
Print + eBook $48.99
READ FOR FREE Free Trial for 7 days. $12.99 p/m after trial. Cancel Anytime! BUY NOW BUY NOW BUY NOW
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 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
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 Audiobook?
Download a zip folder consisting of audio files (in MP3 Format) along with supplementary PDF
READ FOR FREE Free Trial for 7 days. $12.99 p/m after trial. Cancel Anytime! BUY NOW BUY NOW BUY NOW
Subscription FREE
eBook + Subscription $12.99
eBook $39.99
Print + eBook $48.99
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 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
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 Audiobook?
Download a zip folder consisting of audio files (in MP3 Format) along with supplementary PDF
  1. Free Chapter
    Web Mapping Basics
About this book
OpenLayers 3 is one of the most important and complete open source JavaScript mapping libraries today. Throughout this book, you will go through recipes that expose various features of OpenLayers 3, allowing you to gain an insight into building complex GIS web applications. You will get to grips with the basics of creating a map with common functionality and quickly advance to more complicated solutions that address modern challenges. You will explore into maps, raster and vector layers, and styling in depth. This book also includes problem solving and how-to recipes for the most common and important tasks.
Publication date:
March 2016
Publisher
Packt
Pages
304
ISBN
9781785287756

 

Chapter 1. Web Mapping Basics

In this chapter, we cover the following topics:

  • Creating a simple fullscreen map

  • Playing with the map's options

  • Managing the map's stack layers

  • Managing the map's controls

  • Moving around the map view

  • Restricting the map's extent

 

Introduction


This chapter shows us the basics and the important things that we need to know when we start creating our first web-mapping application with OpenLayers.

As we will see in this and the following chapters, OpenLayers is a big and complex framework, but at the same time, it is also very powerful and flexible.

Although we're now spoilt for choice when it comes to picking a JavaScript mapping library (as we are with most JavaScript libraries and frameworks), OpenLayers is a mature, fully-featured, and well-supported library.

In contrast to other libraries, such as Leaflet (http://leafletjs.com), which focuses on a smaller download size in order to provide only the most common functionality as standard, OpenLayers tries to implement all the required things that a developer could need to create a web Geographic Information System (GIS) application.

One aspect of OpenLayers 3 that immediately differentiates itself from OpenLayers 2, is that it's been built with the Google Closure library (https://developers.google.com/closure). Google Closure provides an extensive range of modular cross-browser JavaScript utility methods that OpenLayers 3 selectively includes.

OpenLayers 3 packs a smaller footprint than its predecessor and targets the latest HTML5 and CCS3 capabilities. The trade off, of course, is that legacy browsers will not be as fully featured (primarily, Internet Explorer lower than version 9). As the rate of modern browser adoption ever increases, this disadvantage will soon become a moot point.

The main concept in OpenLayers is, rightly, the map. It represents the view where information is rendered. The map can contain multiple layers, which can be raster or vector layers. Each layer has a data source that serves data with its own format: a .PNG image, a .KML file, and so on. In addition, the map can contain controls, which help interact with the map and its contents; these are pan, zoom, feature selection, and so on.

Let's get started with learning OpenLayers by examples.

 

Creating a simple fullscreen map


When you work in mapping applications, the first and foremost task is the creation of the map itself. The map plays a core role in your application, and this is where you will add and visualize data.

This recipe will guide you through the process of creating our first and very simple web map application.

Getting ready

Programming with OpenLayers mainly boils down to writing HTML, CSS, and, of course, JavaScript. We simply need a text editor to start coding up our recipes. There is a wide variety of text editors available, so just take your pick!

Our HTML file will include some OpenLayers library assets. Although you'll see our examples referencing these assets, we won't show you the file contents of these large files in this book. In order to follow along, begin by downloading the latest OpenLayers source code (http://openlayers.org/download/).

You can find the source code for this example in ch01/ch01-full-screen-map/.

How to do it…

  1. Let's start by first creating a new HTML file with the following content:

    <!doctype html>
    <html>
    <head>
      <meta charset="utf-8">
      <title>Creating a simple full screen map | Chapter 1</title>
      <link rel="stylesheet" href="ol.css">
      <link rel="stylesheet" href="style.css">
    </head>
    <body>
      <div id="js-map" class="map"></div>
      <script src="ol.js"></script>
      <script src="script.js"></script>
    </body>
    </html>

    You'll notice that the OpenLayers files being linked to here are ol.css and ol.js. Our own custom files are style.css and script.js.

    The OpenLayers CSS (ol.css) contains CSS3 animations and styling for HTML elements, such as map controls, that is, the map zooming buttons, and much more.

    Using best practices, the OpenLayers JavaScript (ol.js) and our own custom JavaScript file has been included just before the closing </body> tag to avoid blocking page rendering. Another positive outcome of this is that we can be assured the DOM has loaded before executing our JavaScript.

  2. Next, create a stylesheet (style.css) with the following content:

    .map {
      position: absolute;
      top: 0;
      bottom: 0;
      left: 0;
      right: 0;
    }

    This combined set of CSS rules results in expanding div so that it completely fills the page's available space. Using the .map class selector means that this will target our <div> element that was created earlier:

    <div id="js-map" class="map"></div>

    Tip

    Downloading the example code

    You can download the example code files for all Packt Publishing books that you have purchased from your account at http://www.packtpub.com. If you purchased this book elsewhere, you can visit http://www.packtpub.com/support and register to have the files e-mailed directly to you.

    You can download the code files by following these steps:

    • Log in or register to our website using your e-mail address and password.

    • Hover the mouse pointer on the SUPPORT tab at the top.

    • Click on Code Downloads & Errata.

    • Enter the name of the book in the Search box.

    • Select the book for which you're looking to download the code files.

    • Choose from the drop-down menu where you purchased this book from.

    • Click on Code Download.

    Once the file is downloaded, please make sure that you unzip or extract the folder using the latest version of:

    • WinRAR / 7-Zip for Windows

    • Zipeg / iZip / UnRarX for Mac

    • 7-Zip / PeaZip for Linux

  3. Lastly, create our custom JavaScript file (script.js) and place the following content in it:

    var map = new ol.Map({
      view: new ol.View({
        center: [-15000, 6700000],
        zoom: 5
      }),
      layers: [
        new ol.layer.Tile({
          source: new ol.source.OSM()
        })
      ],
      target: 'js-map'
    });

    Open the file in your browser and witness the result. You will see a map that fills the page with some controls in the top-left corner and map attribution in the bottom-right corner, which is similar to what's shown in the following screenshot:

How it works…

It's pleasing to realize that creating a map with OpenLayers can be quickly achieved with minimal code. However, we aren't reading this book to stand back in awe, we'd rather try to understand how JavaScript has accomplished this.

Initially, it's worth examining the HTML because OpenLayers has been busy making amendments. You'll need to open up your browser development tools. This is normally as easy as right-clicking anywhere on the page and selecting Inspect Element from the context menu. Scroll down to our <div> element that we originally created. It should look similar to the following screenshot:

You'll notice that OpenLayers has modified the content of our previously empty <div>, and inserted a <div class="ol-viewport"> child element, which expands to the total dimensions of the parent element, which we set to fill the screen. You control the size of the map completely through CSS.

Note

OpenLayers prefixes its CSS hooks with ol-.

Within this generated <div> lies a <canvas> element that makes up the map that you see before you. The HTML5 canvas technology is more performant than assembled image DOM elements, which was the default structure in OpenLayers 2.

For the curious, venture further into the other <div> elements, and you'll quickly stumble into the HTML for the map controls. Unlike OpenLayers 2 that used images for map controls, OpenLayers 3 uses only CSS. This means that customizing the map controls is much easier than before.

Let's pull ourselves out of the HTML for a moment and relocate our attention to the JavaScript that got this all working. We'll go through the code piece by piece:

var map = new ol.Map({
  // ...
});

The ol.Map constructor is our entry point to create a map. On instantiation, part of what happens involves the creation of the HTML elements that we looked over earlier. At a minimum, the constructor requires a view, one or more layers, and a target as it's arguments:

view: new ol.View({
  center: [-15000, 6700000],
  zoom: 5
}),

To help us understand the separate steps required to create a map, let's imagine the following analogy. Let's suppose that the map is a vast and scenic world that you're only able to view through binoculars and ol.View is the binoculars. You can tilt your head and spin around (view rotation), move your line of sight to point to somewhere else (changing your view center) and adjust focus for varying objects at a distance (zoom/resolution).

With this analogy in mind, we use our binoculars (the view) to set the starting position. The center xy coordinates are passed in via an array (we'll explore coordinates and projections in more detail as this book progresses). We also provide a zoom level. We have selectively created a subset viewport of the world.

 layers: [
    new ol.layer.Tile({
       source: new ol.source.OSM()
    })
  ],

The layers property of ol.Map expects an array, as you can include multiple layers per map.

The ol.layer.Tile constructor is a subclass of ol.layer.Layer, but it is specifically designed for prerendered tiled images that are structured in grids and organized by zoom levels for specific resolutions.

The source of the tiled layer is derived from the ol.source.OSM constructor, which enables us to effortlessly use the OpenStreetMap tile service. This constructor is a subclass of ol.source.XYZ, which is the format that OSM uses.

target: 'js-map'

Lastly, the target property of ol.Map can either be a string (which must represent the ID of the HTML element), or you can pass in a DOM element instead. Our string, 'js-map', matches up with our HTML element:

<div id="js-map" class="map"></div>

Alternatively, we could have passed in the DOM element:

target: document.getElementById('js-map')

Now that we've covered all the parts of this puzzle, we hope that you've been able to get a better insight behind what's actually going on. This basic knowledge will help you build a solid foundation as we keep moving forward.

There's more…

In our first example, we used up as much of the web page as possible, but we all know that this is not quite the definition of fullscreen! To actually go properly fullscreen, OpenLayers can make use of the HTML5 fullscreen API.

You can find the source code for this example in ch01/ch01-html5-full-screen-map/.

Keep the HTML and CSS exactly the same as the previous version, but modify the JavaScript so that it matches the following:

var map = new ol.Map({
  view: new ol.View({
    center: [-15000, 6700000],
    zoom: 5
  }),
  layers: [
    new ol.layer.Tile({
      source: new ol.source.OSM()
    })
  ],
  controls: ol.control.defaults().extend([
    new ol.control.FullScreen()
  ]),
  target: 'js-map'
});

The watchful among you may have noticed that regardless of the fact that we didn't pass in any controls to our previous version of the map, it still contained the zoom and attribution controls. This is because OpenLayers adds some default controls if none are specified.

controls: ol.control.defaults().extend([
  new ol.control.FullScreen()
]),

We have decided to extend the default controls that OpenLayers normally provides and append the fullscreen control. The extend utility method comes from the Google Closure library, which extends an object with another object in place.

Open the file in your browser and you'll see the new fullscreen control at the top-right corner of the map. Click the button to go fullscreen!

If we wanted to just enable the fullscreen control with no others, we can use the following code:

controls: [
      new ol.control.FullScreen()
],

Although we're passing in just a single control, OpenLayers expects a collection, so it's wrapped inside an array.

We finish this topic having learned how to create a new map from scratch with some custom controls. It's time to move on to the next topic!

         
About the Authors
  • Peter J. Langley

    Peter J. Langley has been developing websites ever since he owned his first computer. He has been working professionally for many years as a lead web developer for various companies and industries as an employee & freelancer. As the influx of available technologies and capabilities in web browsers continues to increase, he has been fortunate enough to play a leading role in the software engineering of some sophisticated solutions, such as web-based GIS applications for Britain's mapping agency, Ordnance Survey. Peter is passionate about the Internet, computing, and software engineering principles. He enjoys working on engaging projects in vibrant atmospheres that quickly deliver value to consumers. He has been sharing how-to guides on his website, www.codechewing.com, for many years. This is a demonstration of his personal desire to encourage people to passionately unite knowledge and thrive from each other's experiences, interests, and perspectives.

    Browse publications by this author
  • Antonio Santiago Perez

    Antonio Santiago Perez is a computer science professional with more than 10 years of experience in designing and implementing systems. Since the beginning of his professional life, his work has been always related to the world of meteorology while working for different companies as an employee or a freelancer. He has experience in development of systems that collect, store, transform, analyze, and visualize data, and he is actively interested in any GIS-related technology with a preference for data visualization. His main field of experience is the Java ecosystem, and he has also actively worked with many related web technologies while looking to improve the client side of web applications. He is a firm believer in software engineering practices and is a follower of agile methodologies, involving customers as the main key to the project's success.

    Browse publications by this author
Latest Reviews (4 reviews total)
Informatief. Niet goedkoop
Good details about each recipe
OpenLayers 3.x Cookbook - Second Edition
Unlock this book and the full library FREE for 7 days
Start now