Published on
Updated on
Updated on

How to Add XYZ Tile Layers to an OpenLayers Map

This article teaches you how to create a simple OpenLayers application with XYZ tile layers. You can use any of the layers on our categorized layer list to add to the application.

Here is a CodePen of the resulting application:

First, let's create an index.html file:

index.html
<!DOCTYPE html>
<html>
  <head>
    <title>OpenLayers - XYZ Tiles Demo</title>
    <meta charset="utf-8" />
    <meta name="viewport" content="width=device-width, initial-scale=1.0, maximum-scale=1, user-scalable=no" />
    <link rel="stylesheet" href="https://cdn.jsdelivr.net/gh/openlayers/openlayers.github.io@master/en/v6.12.0/css/ol.css" />
    <link rel="stylesheet" href="style.css" />
    <script src="https://cdn.jsdelivr.net/gh/openlayers/openlayers.github.io@master/en/v6.12.0/build/ol.js"></script>
  </head>
  <body>
    <div id="map"></div>
    <script src="main.js"></script>
  </body>
</html>

What's happening here:

  • We include OpenLayers CSS file on line 7.
  • We include a CSS file on line 8 that we will create later.
  • We include OpenLayers JavaScript file on line 9.
  • We create a container for the map on line 12, defining 'map' as the id (you can use any id you want).
  • We include a JavaScript file on line 13 that we will create later.

Now, let's create a style.css file to style the map:

style.css
html, body {
  height: 100%;
  margin: 0;
  padding: 0;
}

#map {
  height: 100%;
}

These rules will make our map appear full screen.

Finally, we'll create a main.js file that will handle creating layers and adding them to the map:

main.js
const cartoDBDarkMatter = new ol.layer.Tile({
  source: new ol.source.XYZ({
    url: 'https://{a-d}.basemaps.cartocdn.com/dark_all/{z}/{x}/{y}.png',
    attributions: '&copy; <a href="https://www.openstreetmap.org/copyright">OpenStreetMap</a> contributors &copy; <a href="https://carto.com/attributions">CARTO</a>',
  }),
  maxZoom: 19
});

const map = new ol.Map({
  target: 'map',
  layers: [cartoDBDarkMatter],
  view: new ol.View({
    center: [-167000, 6840000],
    zoom: 8,
  }),
});

Let's break it down:

  • We define the tile layer on lines 1-7 (the highlighted part) and save it to a variable.
  • We initialize the map on lines 9-16, add the created layer and set the map's view to our chosen coordinates and zoom level. By default, OpenLayers uses coordinates in EPSG:3857 (a.k.a. Web Mercator or Spherical Mercator). Here we set the view to some place in England and use 'map' to refer to the map container that we added to the HTML file.

You can pick any of the layers from our categorized layer list to add to your application. Just copy the code to create the layer in the preview application, paste it into your JavaScript file in place of the highlighted part and add it to the map's layers array.