Published on
Updated on
Updated on

How to Add XYZ Tile Layers to a Leaflet Map

This article teaches you how to create a simple Leaflet 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:

<!DOCTYPE html>
    <title>Leaflet - 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="" crossorigin="" />
    <link rel="stylesheet" href="style.css" />
    <script src="" crossorigin=""></script>
    <div id="map"></div>
    <script src="main.js"></script>

What's happening here:

  • We include Leaflet CSS file on line 7.
  • We include a CSS file on line 8 that we will create later.
  • We include Leaflet 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:

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 the map object and adding layers to the map:

const map ='map').setView([52.2, -1.5], 8);

const cartoDBDarkMatter = L.tileLayer('https://{s}{z}/{x}/{y}.png', {
  attribution: '&copy; <a href="">OpenStreetMap</a> contributors &copy; <a href="">CARTO</a>',
  subdomains: 'abcd',
  maxZoom: 19


Let's break it down:

  • We initialize the map on line 1 and set its view to our chosen geographical coordinates and zoom level (here we use coordinates for some place in England). We use 'map' to refer to the map container that we added to the HTML file.
  • We define the tile layer on lines 3-7 (the highlighted part) and save it to a variable.
  • Lastly, we add the created layer to the map.

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 the .addTo(map) command.