How to use Vector Tiles in Leaflet
Tags: tutorial, webdev, maps, javascript
Published: 2023-11-17 16:39:00

[Leaflet](https://buff.ly/3sv80Ax) is a lightweight open-source library for creating online maps. It works efficiently across all major desktop and mobile platforms and can be extended with many plugins.

Leaflet doesn’t support vector tiles by default, but you can use one of the available [plugins to display them](https://buff.ly/46iY9M2). We will use the [Basemaps with Vector Tiles](https://buff.ly/47xHsNC) plugin in this example. You’ll need a MapTiler account to use the plugin, but these are free for non-commercial use and give you access to a lot of great map styles. [You can create a free account here](https://buff.ly/3SMcYUi).

If you want to know the differences between Raster and Vector data and when you should use vector tiles, we’ve added a handy guide to the end of this tutorial: [Vector vs. Raster tiles](#raster-vs-vector-map-tiles-what-is-the-difference-between-the-two-data-types).

## Create a map and display it on a web page
Simple web technologies like HTML, CSS, and JavaScript are required to add a map to our web page. We’ve included all the code you need to create the page below.

### HTML Boilerplate
Create a basic HTML file.

```
<!DOCTYPE html>
<html lang="en">
<head>
  <meta charset="UTF-8">
  <meta name="viewport" content="width=device-width, initial-scale=1.0">
  <title>Display a map</title>
  <style>
    body {
      margin: 0;
      padding: 0;
    }
  </style>
</head>
<body>

</body>
<script>

</script>
</html>
```
Include the Leaflet JavaScript and CSS files in the `head` of your HTML file.

```
<link rel="stylesheet" href="https://unpkg.com/leaflet@1.9.4/dist/leaflet.css" integrity="sha256-p4NxAoJBhIIN+hmNHrzRCf9tD/miZyoHS5obTRR9BMY=" crossorigin="" />
<script src="https://unpkg.com/leaflet@1.9.4/dist/leaflet.js" integrity="sha256-20nQCchB9co0qIjJZRGuk2/Z9VM+kNiyxNV1lvTlZBo=" crossorigin=""></script>
```

### Create a Map container and create a Map object
Create a `<div>` element with a certain id where you want your map to be.

Add `<div>` tag to your page. This div will be the container where the map will be loaded.

```
<body>
  <div id="map"></div>
</body>
```
The div must have a non-zero height.  Create a rule for the style of the map in the CSS of the page. In this example, we are going to make a full-screen map.

```
#map {
    position: absolute;
    top: 0;
    bottom: 0;
    width: 100%;
}
```
Now, in your JavaScript, create a map object. We’ll initialize the map with the id of the container element created before i.e. “map” and set its view to our chosen geographical coordinates  [lat, lng] and a zoom level.

```
const map = L.map('map').setView([0, 0], 2);
```

### Add the Vector Tiles basemap
Leaflet is a JavaScript map API that does not provide any data. Leaflet depends on third parties to provide the basemap. Generally, Leaflet is used with Raster Tiles basemaps like OpenStreetMap, Esri, Bing Maps, MapTiler, etc.

As previously explained, using a vector basemap has multiple advantages over raster maps. That is why we are going to use the [Basemaps with Vector Tiles plugin](https://buff.ly/49DDlBF).

Include the plugin JavaScript and CSS files in the `head` of your HTML file.

> All leaflet plugin libraries must be loaded **after** Leaflet JavaScript

```
<script src="https://cdn.maptiler.com/maptiler-sdk-js/v1.1.2/maptiler-sdk.umd.js"></script>
<link href="https://cdn.maptiler.com/maptiler-sdk-js/v1.1.2/maptiler-sdk.css" rel="stylesheet" />
<script src="https://cdn.maptiler.com/leaflet-maptilersdk/v1.0.0/leaflet-maptilersdk.js"></script>
```
We use the `L.maptilerLayer` class to create a layer to load and display our map.  In your JS code, after the map object creation, write the following line:

```
const mtLayer = L.maptilerLayer({ apiKey: `YOUR_MAPTILER_API_KEY_HERE` }).addTo(map);
```

> Replace YOUR_MAPTILER_API_KEY_HERE with your actual [MapTiler API key](https://buff.ly/46lpYTU).

Using the `L.maptilerLayer` you have:

- All the power of [MapTiler SDK JS](https://buff.ly/3R1FnUW) to use vector tile layers (for data overlays) in your applications without any kind of limitation (show millions of geometries, choropleth maps, etc.).
- Multi-lingual vector tiles basemaps for Leaflet using the MapTiler SDK.
- Use any of the many [professional-looking basemaps](https://buff.ly/3ulepi6) created by MapTiler, or use a map with your own custom basemap.
- Easily change the language of your map without having to create a new basemap.
- Locate the user and center the map accordingly.

## Complete Code and Result

```
<!DOCTYPE html>
<html>
  <head>
    <meta name="viewport" content="initial-scale=1,maximum-scale=1,user-scalable=no" />
    <title>Vector Tiles in Leaflet JS</title>
    <link rel="stylesheet" href="https://unpkg.com/leaflet@1.9.4/dist/leaflet.css" />
    <script src="https://unpkg.com/leaflet@1.9.4/dist/leaflet.js"></script>
    <script src="https://cdn.maptiler.com/maptiler-sdk-js/v1.1.2/maptiler-sdk.umd.js"></script>
    <link href="https://cdn.maptiler.com/maptiler-sdk-js/v1.1.2/maptiler-sdk.css" rel="stylesheet" />
    <script src="https://cdn.maptiler.com/leaflet-maptilersdk/v1.0.0/leaflet-maptilersdk.js"></script>
    <style>
      #map {position: absolute; top: 0; right: 0; bottom: 0; left: 0;}
    </style>
  </head>
  <body>
    <div id="map"></div>
    <script>
      const map = L.map('map').setView([0, 0], 1);
      const mtLayer = L.maptilerLayer({ apiKey: 'YOUR_MAPTILER_API_KEY_HERE' }).addTo(map);
    </script>
  </body>
</html>
```

## Extra features of using the Vector Tiles plugin
### Change the map language

If nothing is specified by default, the plugin uses the language defined in the browser.  To change the map language, use the setLanguage function of the maptilerLayer layer.

```
mtLayer.setLanguage(ja); //change the language to Japanese
```

### Use the built-in basemap styles.
The plugin comes with a list of [built-in basemap styles](https://buff.ly/3ulepi6). It shows the street map by default, but you can easily change the styles using the setStyle function.

```
mtLayer.setStyle(L.MaptilerStyle.DATAVIZ.DARK); //change to dark style map for data visualization
```
Check out the plugin [API reference](https://buff.ly/47gQgYN) for all options and methods. 

## Conclusions
Using a vector basemap has advantages over traditional raster basemaps. You can easily replace your raster basemap with a vector one. The rest of your application and layers will continue to work normally. Just replace the L.TileLayer layer with the L.maptilerLayer.

Example: replace the OpenStreetMap basemap (L.tileLayer)

```
 const rasterLayer = L.tileLayer('https://{s}.tile.openstreetmap.org/{z}/{x}/{y}.png', {
    attribution: '© OpenStreetMap contributors'
}).addTo(map);
```

with the  vector tiles basemap (L.maptilerLayer)

```
const mtLayer = L.maptilerLayer({ apiKey: 'YOUR_MAPTILER_API_KEY_HERE' }).addTo(map);
```

### Raster vs Vector Map Tiles: What Is the Difference Between the Two Data Types?
Web maps based on raster tiles technology are older but still widely used approach by many.

Raster map tiles are actually nothing else than raster images. Zoomable raster maps consist of many raster map tiles (in the .png or .jpg format) placed next to each other, ordered in a pyramid scheme.

Vector tiles also deliver data divided into roughly squared tiles, but they were introduced later. However, these tiles do not consist of raster images; they are made of geometric features such as points, curves, or polygons. Vector tiles are rendered on the client’s side with a style. This is a small text file that defines how certain map elements look and how they are displayed (e.g., a road can be defined as a solid red line placed on top of all map elements).

It is possible to mix raster with vector tiles and get the best out of both, e.g., a satellite map (raster tiles) with an overlay of streets and labels available in different languages (vector tiles).