Displaying the what3words grid on a LeafletJS Map
Updated
Step by step
The what3words API supports the ability to obtain a section of the 3m x 3m what3words grid in GeoJSON format, making it very simple to display on a map.
This tutorial will show you how to integrate the what3words grid with LeafletJS. We also have tutorials demonstrating its use with both Mapbox and Google Maps.
LeafletJS is an open source JavaScript mapping engine. More information can be found at https://leafletjs.com/reference-1.5.0.html.
1Step 1: Get API key#
Get an API key
You will need a what3words API key to complete this tutorial.
2Step 2: Installation#
To load the JavaScript wrapper for the what3words API, use a script tag like the one in the following example. Replace YOUR-API-KEY with your what3words API key to get started.
Note: We prefer to use a fixed version of the production version of your integrations. A specific version can also be specified within the script to ensure a predictable version of the component is loaded, for example@5.0.0. A log of versions can be found here.
<script src="https://cdn.what3words.com/javascript-components@5.0.0/dist/what3words/what3words.js?key=YOUR-API-KEY"></script>The URL contained in the script tag is the location of a JavaScript file that loads everything you need for using the JavaScript wrapper for the what3words API.
The key parameter contains your application’s API key.
You will also need to load the LeafletJS API, for example:
<script src="https://unpkg.com/leaflet@1.5.1/dist/leaflet.js" integrity="sha512-GffPMF3RvMeYyc1LWMHtK8EbPv0iNZ8/oTtHPx9/cc2ILxQ+u905qIwdpULaqDkyBKgOaB57QTMg7ztg8Jm2Og==" crossorigin=""></script>3Step 3: Map style#
Within the head tag, we need to set style properties for LeafletJS. In this example, we’ll set the map to display full screen.
<link rel="stylesheet" href="https://unpkg.com/leaflet@1.5.1/dist/leaflet.css" integrity="sha512-xwE/Az9zrjBIphAcBb3F6JVqxf46+CDLwfLMHloNu6KEQCAWi6HcDUbeOfBIptF7tcCzusKFjFw2yuvEpDL9wQ==" crossorigin="" />
<style>
#map {
height: 100%;
}
html, body {
height: 100%;
margin: 0;
padding: 0;
}
</style>4Step 4: Map initialisation#
Within the body tag, we need to create a new div element to contain the map component, as well as initialise it using the LeafletJS API.
<div id="map"></div>
<script>
var map = L.map('map').setView([51.505, -0.09], 19);
L.tileLayer('https://{s}.tile.openstreetmap.org/{z}/{x}/{y}.png', {
attribution: '© <a href="https://www.openstreetmap.org/copyright">OpenStreetMap</a> contributors',
maxNativeZoom:19,
maxZoom:25
}).addTo(map);
</script>5Step 5: Grid overlay#
The what3words grid can be displayed on top of a LeafletJS Map adding a GeoJSON layer to the map.
Because only a segment of grid section can be requested, we need to obtain a new grid section each time the map is panned or zoomed.
<script>
function drawGrid() {
const zoom = map.getZoom();
const loadFeatures = zoom > 17;
if (loadFeatures) { // Zoom level is high enough
var ne = map.getBounds().getNorthEast();
var sw = map.getBounds().getSouthWest();
// Call the what3words Grid API to obtain the grid squares within the current visble bounding box
what3words.api
.gridSection({
boundingBox: {
southwest: {
lat: sw.lat,
lng: sw.lng
},
northeast: {
lat: ne.lat,
lng: ne.lng
}
},
format: "geojson"
}).then(function(data) {
// If the grid layer is already present, remove it as it will need to be replaced by the new grid section
if (typeof grid_layer !== 'undefined') {
map.removeLayer(grid_layer);
}
// Create a new GeoJSON layer, based on the GeoJSON returned from the what3words API
grid_layer = L.geoJSON(data, {
style: function() {
return {
color: '#777',
stroke: true,
weight: 0.5
};
}
}).addTo(map);
}).catch(console.error);
} else {
// If the grid layer already exists, remove it as the zoom level no longer requires the grid to be displayed
if (typeof grid_layer !== 'undefined') {
map.removeLayer(grid_layer);
}
}
}
map.whenReady(drawGrid);
map.on('move', drawGrid);
</script>Full example
The example below takes the step by step guide and puts them into a complete, working example.
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8" />
<meta name="viewport" content="width=device-width, initial-scale=1.0" />
<meta http-equiv="X-UA-Compatible" content="ie=edge" />
<script src="https://cdn.what3words.com/javascript-components@5.0.0/dist/what3words/what3words.js?key=YOUR-API-KEY"></script>
<link
rel="stylesheet"
href="https://unpkg.com/leaflet@1.5.1/dist/leaflet.css"
integrity="sha512-xwE/Az9zrjBIphAcBb3F6JVqxf46+CDLwfLMHloNu6KEQCAWi6HcDUbeOfBIptF7tcCzusKFjFw2yuvEpDL9wQ=="
crossorigin=""
/>
<script
src="https://unpkg.com/leaflet@1.5.1/dist/leaflet.js"
integrity="sha512-GffPMF3RvMeYyc1LWMHtK8EbPv0iNZ8/oTtHPx9/cc2ILxQ+u905qIwdpULaqDkyBKgOaB57QTMg7ztg8Jm2Og=="
crossorigin=""
></script>
<title>Grid Section Map Overlay (Leaflet)</title>
</head>
<body>
<div id="map" style="width: 100%; height: 400px;"></div>
<script>
var map = L.map("map").setView([51.505, -0.09], 19);
L.tileLayer("https://{s}.tile.openstreetmap.org/{z}/{x}/{y}.png", {
attribution:
'© <a href="https://www.openstreetmap.org/copyright">OpenStreetMap</a> contributors',
maxNativeZoom: 19,
maxZoom: 25
}).addTo(map);
</script>
<script>
function drawGrid() {
const zoom = map.getZoom();
const loadFeatures = zoom > 17;
if (loadFeatures) {
// Zoom level is high enough
var ne = map.getBounds().getNorthEast();
var sw = map.getBounds().getSouthWest();
// Call the what3words Grid API to obtain the grid squares within the current visble bounding box
what3words.api
.gridSection({
boundingBox: {
southwest: {
lat: sw.lat,
lng: sw.lng
},
northeast: {
lat: ne.lat,
lng: ne.lng
}
},
format: "geojson"
})
.then(function (data) {
if (typeof grid_layer !== "undefined") {
map.removeLayer(grid_layer);
}
grid_layer = L.geoJSON(data, {
style: function () {
return {
color: "#777",
stroke: true,
weight: 0.5
};
}
}).addTo(map);
})
.catch(console.error);
} else {
if (typeof grid_layer !== "undefined") {
map.removeLayer(grid_layer);
}
}
}
map.whenReady(drawGrid);
map.on("move", drawGrid);
</script>
</body>
</html>