Search icon CANCEL
Subscription
0
Cart icon
Your Cart (0 item)
Close icon
You have no products in your basket yet
Arrow left icon
Explore Products
Best Sellers
New Releases
Books
Videos
Audiobooks
Learning Hub
Conferences
Free Learning
Arrow right icon
Arrow up icon
GO TO TOP
OpenLayers 3.x Cookbook

You're reading from   OpenLayers 3.x Cookbook This book will provide users with a variety of recipes that illustrate different features present in OpenLayers 3

Arrow left icon
Product type Paperback
Published in Mar 2016
Publisher
ISBN-13 9781785287756
Length 304 pages
Edition 2nd Edition
Languages
Arrow right icon
Authors (2):
Arrow left icon
Antonio Santiago Antonio Santiago
Author Profile Icon Antonio Santiago
Antonio Santiago
Peter J. Langley Peter J. Langley
Author Profile Icon Peter J. Langley
Peter J. Langley
Arrow right icon
View More author details
Toc

Table of Contents (9) Chapters Close

Preface 1. Web Mapping Basics FREE CHAPTER 2. Adding Raster Layers 3. Working with Vector Layers 4. Working with Events 5. Adding Controls 6. Styling Features 7. Beyond the Basics Index

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 to do it…

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:

How it works…

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!

There's more…

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!

You have been reading a chapter from
OpenLayers 3.x Cookbook - Second Edition
Published in: Mar 2016
Publisher:
ISBN-13: 9781785287756
Register for a free Packt account to unlock a world of extra content!
A free Packt account unlocks extra newsletters, articles, discounted offers, and much more. Start advancing your knowledge today.
Unlock this book and the full library FREE for 7 days
Get unlimited access to 7000+ expert-authored eBooks and videos courses covering every tech area you can think of
Renews at $19.99/month. Cancel anytime
Banner background image