Introduction to Leaflet
Welcome to the introductory course to Leaflet.js

Creating interactive maps on the Web has never been easier.
With the Leaflet JavaScript library, you’ll learn how to represent locations, routes and data, and enrich your maps with markers, styles, interactions and much more.


Course objective

The aim of this course is to enable you to create interactive maps using Leaflet.
At the end of the program, you’ll be able to :

  • Display a map centered on a location,
  • Add markers, polygons, images, etc.,
  • Stylize and customize your map objects,
  • Integrate interactions (clicks, hovers, popups),
  • And even publish your map on the Web.

No previous experience with Leaflet is required. A basic knowledge of HTML/JavaScript is useful but not essential: everything is explained step by step.


Course organization

Each session follows a logical progression:

  1. A summary slide show to introduce key concepts
  2. An explanatory text detailing each point
  3. A practical exercise to apply what you’ve learned
  4. An accessible answer key to check your work

Recommended duration per session: approx. 1-2 hours.
You can follow the pace independently, at your convenience.


Materials required

  1. A Web browser (Chrome, Firefox…)
  2. A code editor (Visual Studio Code, or even an online editor such as JSFiddle or CodePen)
  3. An Internet connection (to load the background maps)
  4. Download the starter kit here, to be unzipped in a directory of your choice.


A simple, active method

This course emphasizes learning by doing.
The aim is not just to read, but to test, modify and experiment. The more you play with the code, the more naturally you’ll retain the concepts.

Let’s get started! Let’s get started!

Loader Loading…
EAD Logo Taking too long?

Reload Reload document
| Open Open in new tab

Slide 1 :What is Leaflet?

Introduction to Leaflet

Leaflet is a lightweight, powerful open-source JavaScript library for creating interactive, dynamic maps on web pages. It is one of the most popular tools for web mapping, and is widely used for its simplicity and ability to integrate with a variety of geographic data sources.

Leaflet’s key features

  • Lightweight: Leaflet is a very lightweight library (around 40 Kb compressed), making it ideal for web applications where performance is essential.
  • Ease of use: With its simple, clear syntax, Leaflet is accessible even to JavaScript beginners.
  • Extensibility: Although the basic library offers essential functionality for interactive maps, Leaflet can be extended with numerous plugins to add additional features (e.g. layer management, geolocation, drawing of geographic shapes, etc.).
  • Compatibility with other formats: Leaflet can easily be used with raster tiles (map images) and vector data (GeoJSON, KML, etc.).

Why use Leaflet?

Leaflet lets you build web maps to meet a wide range of needs, from simple location maps to complex geospatial data visualizations. Here are just a few examples of Leaflet use cases:

  • Displaying interactive maps with tiles like OpenStreetMap, Mapbox, or other tile services.
  • Creation of lightweight Geographic Information System (GIS) maps for visualization of geospatial data.
  • Real-time tracking maps (for example, to track vehicles or people).
  • Geolocation applications, to display positions on maps.
  • Maps used in tourism applications, where points of interest or routes are indicated.

Slide 2: Basic components

1.The map (L.map)

This is the main container for your mapping application.

let map = L.map('map').setView([48.8566, 2.3522], 13);  // Paris avec un zoom de 13


2. Map backgrounds (tiles)

These are images cut into small tiles (256×256 px) loaded according to zoom level and position.

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


3.Markers (L.marker)

Markers indicate a precise position on the map (often with an icon or symbol).

L.marker([48.8566, 2.3522]).addTo(map)
  .bindPopup('Paris').openPopup();


4.Vector shapes

Leaflet lets you draw :

  • Polygons (L.polygon)
  • Polylines (L.polyline)
  • Circles (L.circle)
  • Rectangles (L.rectangle)

Example :

L.polygon([
  [48.85, 2.35],
  [48.85, 2.37],
  [48.87, 2.37]
]).addTo(map);


5.Popups and tooltips

To display information on hover or click.

marker.bindPopup(“Here's a popup”);
marker.bindTooltip(“A little tooltip”, {permanent: true});


6.Layer control (L.control.layers)

Switches between several map backgrounds or information layers.

let baseMaps = {
  "OSM": osmLayer,
  "Satellite": satelliteLayer
};

let overlayMaps = {
  "Réseaux": networkLayer
};

L.control.layers(baseMaps, overlayMaps).addTo(map);


7.Events

Each element (map, marker, polygon, etc.) can listen to events: clicks, hovers, zooms, and so on.

map.on('click', function(e) {
alert("Coordinates: ” + e.latlng);
});


8.GeoJSON layers

For displaying dynamic vector data (often from databases or files).

L.geoJSON(geojsonData).addTo(map);


9.Plugins

Leaflet has a large community. You can add functions such as search, clusters, metrics, etc., via plugins.

Examples include :

  • Leaflet.draw (interactive drawing)
  • Leaflet.markercluster
  • Leaflet.fullscreen

Slide 3: Example of a leaflet card

Basic example of using Leaflet

Explanation: This slide shows how to initialize a map with Leaflet. The sample code shows how to :

  • Initialize the map with L.map(‘id’).
  • Position the map at the center with setView(), defining geographic coordinates (latitude, longitude) and zoom level.
  • Add a tile layer with L.tileLayer(), using free tiles from OpenStreetMap.

The aim is to understand how to set the basic parameters for displaying a Leaflet map.

Here’s a simple example of how to initialize a Leaflet map and add a marker:

exemple_leaflet.html

<!DOCTYPE html>

<html>

<head>

    <title>Exemple Leaflet</title>

    <meta charset=”utf-8″ />

    <meta name=”viewport” content=”width=device-width, initial-scale=1.0″>

    <link rel=”stylesheet” href=”https://unpkg.com/leaflet/dist/leaflet.css” />

    <style>

        #map { height: 400px; }

    </style>

</head>

<body>

    <h3>Ma première carte avec Leaflet</h3>

    <div id=”map”></div>

    <script src=”https://unpkg.com/leaflet/dist/leaflet.js”></script>

    <script>

        var map = L.map(‘map’).setView([48.8566, 2.3522], 13);  // Coordonnées de Paris

        // Ajout d’une couche de tuiles

        L.tileLayer(‘https://{s}.tile.openstreetmap.org/{z}/{x}/{y}.png’, {

            attribution: ‘&copy; <a href=”https://www.openstreetmap.org/copyright”>OpenStreetMap</a> contributors’

        }).addTo(map);

        // Ajout d’un marqueur

        L.marker([48.8566, 2.3522]).addTo(map)

            .bindPopup(“<b>Paris</b><br>La capitale de la France”)

            .openPopup();

    </script>

</body>

</html>

This code creates a map centered on Paris, with a marker that displays a popup containing descriptive text. Users can zoom in, move the map around, and interact with it.

View the map in a new tab.

Slide 4: Adding a marker and popup

Explanation: This slide shows how to add a marker to the map. The marker represents a geographical point, and once added, a popup can be associated to display information when the user clicks on the marker. The code L.marker().addTo(map) is used to create a marker, and bindPopup() to link a popup containing a message.

Slide 5: Personalizing a marker with an icon

Explanation: Markers in Leaflet can be customized with icons to make them more visual and representative. This slide shows how to use the L.icon() class to create a custom icon, then apply it to the marker via the icon option. This makes it possible to customize the marker’s appearance according to the context of the application (for example, a marker representing a gas station or hotel with specific icons).

Slide 6: Adding multiple markers to a map

Explanation: When several points of interest are to be added to the map, this slide explains how to proceed. You can create several markers, each with specific coordinates, and then add them to the map. An example code shows the creation of an array of coordinates, then the forEach() loop to add the markers to the map. This makes it possible to add hundreds or thousands of points without code overload.

Slide 7: Basic structure of a leaflet page

Summary of key elements:

  • A <div id="map"> to contain the map.
  • Mandatory CSS to define the size of the container.
  • Links to Leaflet files (CSS + JS).
  • A JavaScript script to :

    • create the map,
    • add a background map,
    • possibly add layers, markers, popups, etc.

<!DOCTYPE html>
<html>
<head>   

<title>Ma première carte Leaflet</title>   

<meta charset=”utf-8″ />   

<meta name=”viewport” content=”width=device-width, initial-scale=1.0″>

<link rel=”stylesheet” le CDN Leaflet />   

<style>       
Définition de la carte
</style>
</head>
<body>   
<h1>Carte interactive avec Leaflet</h1>   

<div id=”map”></div>   
<script>

        …    Les éléments de la carte
</script>
</body>
</html>

Practical Exercise

Exercise – Session 1: My first interactive map

Objective:

Create an interactive map centered on your city, with three points of interest of your choice (tourist sites, personal places, etc.).


Steps to follow :

Create an index.html file
This file will contain the code for your map.

Add Leaflet resources
In the HEAD tag, paste this code to load the Leaflet library:

  • <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>

Prepare a display area for the map
In the BODY , add a div with a map identifier and give it a height in a tag or directly in CSS

  • <div id=”map” style=”height: 400px;”></div>

Initialize the map
In a tag <script>

  • var map = L.map(‘map’).setView([48.8566, 2.3522], 13); // Creates a map centered on your city (Paris, for example)
  • L.tileLayer(‘https://{s}.tile.openstreetmap.org/{z}/{x}/{y}.png’, { attribution: ‘© OpenStreetMap contributors’ }).addTo(map);// Add a background layer (OpenStreetMap)

Add 3 custom markers
Place three points on your map with information bubbles:

  • L.marker([48.8584, 2.2945]).addTo(map).bindPopup(“Tour Eiffel”);
  • L.marker([48.8606, 2.3376]).addTo(map).bindPopup(“Louvre”);
  • L.marker([48.8738, 2.2950]).addTo(map).bindPopup(“Arc de Triomphe”);


Bonus:

Add an interaction to display coordinates when clicked on the map:

map.on(‘click’, function(e) {

    alert(“Coordonnées : ” + e.latlng);

});


Expected result:

A map appears in the center of your browser, zoomed in on your city, with three markers. Clicking on each marker opens a tooltip. Clicking anywhere on the map displays the point’s coordinates.

See the result for Paris in a new tab

See the result for Rodrigues Island in a new tab.

Si cet article vous a intéressé et que vous pensez qu'il pourrait bénéficier à d'autres personnes, n'hésitez pas à le partager sur vos réseaux sociaux en utilisant les boutons ci-dessous. Votre partage est apprécié !

Leave a Reply

Your email address will not be published. Required fields are marked *