What is Leaflet?

Leaflet is a JavaScript library that allows you to create interactive maps in a very simple way. It’s open source and mobile-friendly, which in Christian terms means that it gets along very well with mobiles.

Leaflet was created in 2011 by Volodymyr Agafonkin, a Ukrainian developer who is currently suffering from the war in his country and who warns us about it when we enter the website.

Leaflet is located on https://leafletjs.com/, and contains a lot of documentation about its API, with multiple tutorials and a lot of plugins with which you can do a lot of cool things. When you enter the website, and see the examples, it may seem that it is poor and that there is little you can do with this cartographic library, but when you see examples, you quickly realize that it is very powerful. For example, we can see some of them here.

In short, you only have to look at the table of companies that appear on the home page itself.

How does Leaflet work?

Getting started with creating a map in Leaflet is relatively straightforward. You just have to follow the starting tutorial that comes on the web, but since it is understood that we know some things, here I am going to break it down a little better so that there is no doubt.

Let’s start by creating a map on a peeled and peeled html file, here we are not going to talk about WordPress or anything like that, we are going to go to the base to understand how it works, and then everyone can apply it wherever they want and how they know.

Well, let’s start with this simple html file:

<! DOCTYPE html>
<html lang="en-GB">
<head>
	<meta charset="UTF-8">
	<meta http-equiv="X-UA-Compatible" content="IE=edge">
	<meta name="viewport" content="width=device-width, initial-scale=1.0">
	<title>What is Leaflet</title>
</head>
<body>
	
</body>
</html>

As you can see, it’s simple, the HTML5 doctype tag is defined, the tag that defines the language of the page, the head tags, where several parameters of the website are defined and, within which, we will have to make the call to Leaflet and, finally, the body tags, where we will show and build the map.

It’s that simple.

Call to the Leaflet bookstore.

It is possible to download the library to self-host it on the hosting itself, it would be advisable, for example, if we were creating a plugin for WordPress, so as not to make external calls. However, the JS library is very light (only 42 kb).

But let’s follow the example set by its author. So we’re going to make the call to the web directly. To do this, what we will do is insert inside the head tags, just below the meta tags, the call to the CSS file that accompanies Leaflet.

To do this, we will enter the following code:

<link rel="stylesheet" href="https://unpkg.com/leaflet@1.8.0/dist/leaflet.css"
   integrity="sha512-hoalWLoI8r4UszCkZ5kL8vayOGVae1oxXe/2A4AO6J9+580uKHDO3JdHb7NzwwzK5xr/Fs0W40kiNHxM9vyTtQ=="
   crossorigin=""/>

Next, and this is very important and warns us, the next line is the one that loads the JavaScript library itself after having loaded the CSS style file. If not, it won’t work.

Well, we’re obedient and we do.

 <script src="https://unpkg.com/leaflet@1.8.0/dist/leaflet.js"
   integrity="sha512-BB3hKbKWOc9Ez/TAwyWxNXeoV9c1v6FIeYiBieIWkpLjauysF18NzgR1MBNBXf8/KABdlkX68nAhlwcDFLGPCQ=="
   crossorigin=""></script>

In this way, we would already have our website ready to use Leaflet. But we’re still not going to be able to see anything on the web.

Be careful, it is important to warn, as can be seen in the code, that the files for a certain version of the library are being loaded. At the time of writing, this is version 1.8.0.

Painting the Map

Well, let’s get to what you really want to see. Let’s paint a map once and for all. To do this, we go inside the body tags, which is where we have to include everything we want to show on the web (in case you don’t know HTML).

We will paint the map inside a div tag that we will call id map or whatever we want, but to avoid messing up, we can call it map.

<div id="map"></div>

But this is still just nothing, an invisible horizontal line on our map, so we need to give it some measurements. We’re going to do this by applying CSS styles to it. To do this, we go back inside the head tags, and just before the title tag, we add some style tags.

Within them we will add the measurements of the map box, which in our example we are going to make 800px wide by 500px high. Therefore, the code will look like this:

<style>
    #map {
        width: 800px;
        height: 500px;
    }
</style>

And you’ll say, but up to this point I still haven’t seen anything. Well, because we have to initialize the map, and tell it what we want to see. To do this, under the div tag where we’re going to display the map, we’ll add some script tags, which is where we’re actually going to give the instructions to “paint” our map.

The first thing is to start the map and tell it what place in the world we want it to show us. I want the map to appear in Granada. To do this, I need to know the geographical coordinates of the place I want to display. I’m going to throw it at the top of my game and I’m going to show the Alhambra on my map. If I go to Google maps and right-click on it, I get a context menu where the first thing I see are the geographical coordinates of the monument. When you click on them, they are copied to the clipboard. These are: 37.17704280619901, -3.5915198660469008

Menú contextual con las coordenadas geográficas en Google Maps

The first number is latitude, i.e. the horizontal lines that appear on the maps, and the second number is the longitude, i.e. the vertical lines that appear on the map. In the case of the former, being positive indicates that it is above the equator by 37º and something, while the latter indicates, being negative, that it is 3º east of the famous Greenwich meridian. The meridian 0.

The line we’re going to add inside the style tags is this:

var map = L.map('map').setView([37.17704280619901, -3.5915198660469008], 13);

What we have done is define the map variable and initialize the map with the object L (for Leaflet) (in the background you can hear the walrus clapping its hands). This basically paints the canvas inside the div, and to tell it where we want to place the center of the map (the point that’s going to be in the center of the map), we use the setView method, which is where we add brackets the coordinates, and the degree of zoom that we want to apply to the map.

The thing is, right now you may only be seeing a gray box. This is because we haven’t told you what cartographic base we want to add. To do this, we will use the tilelayer method.

Mapa vacío

Here we’re going to directly paste this code:

L.tileLayer('https://{s}.tile.openstreetmap.org/{z}/{x}/{y}.png', {
    maxZoom: 19,attribution
    : ' © OpenStreetMap'
}).addTo(map);

We’re not going to go into too much detail, but basically it specifies the URL where it is located (with certain parameters), the maximum zoom that is allowed and the attribution, which is the text that you see in the corner of some maps.

The result is as follows:

Mapa con el zoom alto

As we can see, we are very far from the Alhambra, it is barely distinguishable. We can change the zoom level on the line where we set the map view.

var map = L.map('map').setView([37.17704280619901, -3.5915198660469008], 17);

As you can see, things have changed a lot.

Mapa con el zoom bajo

Well, we already have our map painted, and it hasn’t been that difficult either, if you notice, the complete code has been as follows:

<! DOCTYPE html>
<html lang="en-GB">
<head>
	<meta charset="UTF-8">
	<meta http-equiv="X-UA-Compatible" content="IE=edge">
	<meta name="viewport" content="width=device-width, initial-scale=1.0">
	<link rel="stylesheet" href="https://unpkg.com/leaflet@1.8.0/dist/leaflet.css"
	integrity="sha512-hoalWLoI8r4UszCkZ5kL8vayOGVae1oxXe/2A4AO6J9+580uKHDO3JdHb7NzwwzK5xr/Fs0W40kiNHxM9vyTtQ=="
	crossorigin=""/>
	<script src="https://unpkg.com/leaflet@1.8.0/dist/leaflet.js"
   integrity="sha512-BB3hKbKWOc9Ez/TAwyWxNXeoV9c1v6FIeYiBieIWkpLjauysF18NzgR1MBNBXf8/KABdlkX68nAhlwcDFLGPCQ=="
   crossorigin=""></script>
   <style>
		#map {
			width: 800px;
			height: 500px;
		}
   </style>
	<title>What is Leaflet</title>
</head>
<body>
	<div id="map"></div>
	<script>
		var map = L.map('map').setView([37.17704280619901, -3.5915198660469008], 17);
		L.tileLayer('https://{s}.tile.openstreetmap.org/{z}/{x}/{y}.png', {
			maxZoom: 19,attribution
			: ' © OpenStreetMap'
		}).addTo(map);
	</script>
</body>
</html>

If you notice, at the end of the tileLayer method, the addTo command is executed, which tells it to add that layer to the map object we create by declaring the variable of the same name.

Can we do this a little more elegantly?

Yes, I had to explain it to you, but I don’t like spaghetti code. So we’re going to give it a little twist and we’re going to modularize the thing a little bit to make it a little bit more elegant. To do this, we’re going to take the changes made using CSS to a stylesheet that we’re going to call style.css and load it externally. The code will look like this:

<head>
	<meta charset="UTF-8">
	<meta http-equiv="X-UA-Compatible" content="IE=edge">
	<meta name="viewport" content="width=device-width, initial-scale=1.0"><
	link rel="stylesheet" href="https://unpkg.com/leaflet@1.8.0/dist/leaflet.css"
	integrity="sha512-hoalWLoI8r4UszCkZ5kL8vayOGVae1oxXe/2A4AO6J9+580uKHDO3JdHb7NzwwzK5xr/Fs0W40kiNHxM9vyTtQ=="
	crossorigin=""/>
	<script src=" https://unpkg.com/leaflet@1.8.0/dist/leaflet.js"
   integrity="sha512-BB3hKbKWOc9Ez/TAwyWxNXeoV9c1v6FIeYiBieIWkpLjauysF18NzgR1MBNBXf8/KABdlkX68nAhlwcDFLGPCQ=="
   crossorigin=""></script><
   link rel="stylesheet" href="style.css">
	<title>What is Leaflet</title>
</head>

On the other hand, we are going to extract all the JavaScript code with which we have shaped the map, and place it in a .js file and link it from the file index.html as it should, leaving the body as follows.

<body>
	<div id="map"></div>
	<script src="mapa.js"></script>
</body>

As you can see, the index.html is very clean. And the style.css and mapa.js files will look like this.

/* style.css */
#map {
	width: 800px;
	height: 500px;
}

mapa.js var map = L.map('map').setView([37.17704280619901, -3.5915198660469008], 17);
		L.tileLayer('https://{s}.tile.openstreetmap.org/{z}/{x}/{y}.png', {
			maxZoom: 19,attribution
			: ' © OpenStreetMap'
		}).addTo(map);

And what else can I do with Leaflet?

Obviously, Leaflet doesn’t stop at showing a map and that’s it. Its power lies precisely in the fact that we can add all kinds of markers (using the marker method, circles, polygons, small popup-type posters, etc. Also, since this is JavaScript, we can make these elements interact based on user-generated events.

Polígonos, marcadores y popups.

But, in addition, Leaflet has a lot of plugins that allow you to do multiple actions such as searching, editing geometries, animations, making heat maps, geoprocessing (as in a GIS), etc.

As you can see, this is a very powerful tool that we will talk about at length in this blog, which I recommend you investigate.

Tell me, do you have experience with Leaflet? Share with me projects you’ve done with this tool.