Leaflet JS is one of the most exciting discoveries I’ve come across in the latest years. It is one of the most powerful mapping libraries you’ll find around, competing with Google’s API, ESRI and Mapbox thanks to its great community and the awesome plugins that have been developed for it.

Open-source FTW 🤟

(See the code for above map in this post with a few more Leaflet samples)

1. Set up.

All you need to use Leaflet JS is the following:

  • A web browser with html and javascript compatibility (any modern browser like Firefox, Opera, Chrome, Edge, Vivaldi, etc will do).
  • Any text editor.
    • [OPTIONAL] A web server to host your resulting webpage and make it accessible via internet. In any case, you can always run the file locally except for some special features.

2. Integrating Leaflet JS in any webpage.

Being a library, you only need to link its scripts to make use of it.

Start by creating a new file with a basic html structure and extension .html. I always use and recommend w3schools for any help:

Add Leaflet's funcitonalities to the HTML file by including the following code inside some <head> tags:

<head>
.....
<link rel="stylesheet" href="https://unpkg.com/[email protected]/dist/leaflet.css"
  integrity="sha512-xodZBNTC5n17Xt2atTPuE1HxjVMSvLVW9ocqUKLsCC5CXdbqCmblAshOMAS6/keqq/sMZMZ19scR4PsZChSR7A=="
  crossorigin=""/>
<script src="https://unpkg.com/[email protected]/dist/leaflet.js"
  integrity="sha512-XQoYMqMTK8LvdxXYG3nZ448hOEQiglfqkJs1NOQV44cWnUrBc8PkAOcXy20w0vlaXaVUearIOBhiXZ5V3ynxwA=="
  crossorigin=""></script>
.....
</head>

This method will read the library from the internet, but you can download the library files from Leaflet's website to your PC and make proper reference to the local files in your html code:https://leafletjs.com/download.html

<link rel="stylesheet" href="/path/to/leaflet.css" />
<script src="/path/to/leaflet.js"></script>

This options will make use of a local copy of the library and won't be affected by changes to the live repository. It also allows you to adapt the code locally to suit your application.

3. Adding a map to html <body> with Leaflet JS

Location inside html <body>

Leaflet will add its components inside a <div> element which you can place anywhere inside your html <body> tags to suit your design. You need to specify a div "id" in order to refer to it later. I am using "mapid" for this example:

<div id="mapid" style="height:500px;"></div>

The map will be affected by CSS properties assigned to the div tag (#mapid in my case). This will modify how the div element fits and looks in your website.

As an example, I'll modify the frame to be round with a 30px radius, instead of the default square edge. We'll add this code as CSS inside <style> tags. Uncomment these lines to see the difference.

<style>
#mapid{border-radius: 30px;}
</style>

Define the map in javascript

Let's now add the map object itself. This is done using the library functions (which start with L). We'll add all this function inside the <script> tags as they make use of javascript.

  • Define the map object. Make use of the function "L.map" and refer to the "mapid" div element. Then define the start view coordinates and zoom level with "L.setView".

    I am going to set the center of the view approximately in Miami (make a google search and extract its latitude and logitude coordinates: 25.75, -80.2. The zoom range will be set to 12 so it's close enough. Larger values mean bigger zoom in and smaller values provide a wider view.
var map = L.map('mapid').setView([25.75, -80.2], 12);
  • Define the base layer. Web-based maps make use of tiled images which are loaded dinamically according to your navigation across the map. We can use the "L.tileLayer" function and any of the following tiled services very well put together in this post, which includes Open Street Maps (OSM), Google Maps, and ESRI services. Being will be using the OSM basemap for this example:
L.tileLayer("http://a.tile.openstreetmap.org/{z}/{x}/{y}.png", {/*no properties*/
}).addTo(map);
  • Finally, let's add a marker, a basic functionality you will want in most maps. We can set the text inside "bindPopup" being able to format with html tags. "openPopup" function displays the pop up directly at start.
//marker object
var marker = L.marker([25.77, -80.13]).addTo(map);

//pop up object attached to marker object
marker.bindPopup("<b>I'm in</b><br>Miami Beach!").openPopup();

Final result.

The rectangle below is a HTML block with all the code above put together. It should which display a OSM basemap centered in Miami with a marker in Miami Beach.


The source code inside the HTML block above is exactly the following:

<!DOCTYPE html>
<html>

<head>
<meta http-equiv="Content-Type" content="text/html; charset=UTF-8">

<link rel="stylesheet" href="https://unpkg.com/[email protected]/dist/leaflet.css"
  integrity="sha512-xodZBNTC5n17Xt2atTPuE1HxjVMSvLVW9ocqUKLsCC5CXdbqCmblAshOMAS6/keqq/sMZMZ19scR4PsZChSR7A=="
  crossorigin=""/>
<script src="https://unpkg.com/[email protected]/dist/leaflet.js"
  integrity="sha512-XQoYMqMTK8LvdxXYG3nZ448hOEQiglfqkJs1NOQV44cWnUrBc8PkAOcXy20w0vlaXaVUearIOBhiXZ5V3ynxwA=="
  crossorigin=""></script>

</head>

<style>
#mapid{border-radius: 30px;}
</style>

<body>
	<div id="mapid" style="height:500px;"></div>
</body>

<script>

//leaflet map object
var map = L.map('mapid').setView([25.75, -80.2], 12);

//tiled basemap object
var googleMaps = L.tileLayer("http://a.tile.openstreetmap.org/{z}/{x}/{y}.png", {/*no properties*/
}).addTo(map);

//marker object
var marker = L.marker([25.77, -80.13]).addTo(map);

//pop up object attached to marker object
marker.bindPopup("<b>I'm in</b><br>Miami Beach!").openPopup();


</script>
</html>

TIP! You can copy paste this code in a text file with .html extension and preview locally in a browser.

Don't miss the Docs and Plugins sections in the Leaflet JS website. There are plenty of features that you can add to your map. The most interesting are:

I hope you enjoyed this introduction to Leaflet and you can make good use of it. Also, if you can, contribute in its development or spread its use!

You can keep reading a cool use of Leaflet in our article about Turf integration on Leaflet: web-based GIS operations come true.

References