Leaflet tutorial: session 5

Loader Loading…
EAD Logo Taking too long?

Reload Reload document
| Open Open in new tab

Contenu

Slide 1: Key events in Leaflet

In Leaflet, events play a key role in making maps interactive and responsive. Indeed, Leaflet can handle a wide range of events that occur on the map, layers or specific objects (such as markers or polygons). These events react to user actions such as clicks, mouse movements, zooms, view changes and so on. Here’s an overview of the main events in Leaflet, used to add interactivity to your maps.

  • click’ – click on an element or on the map
  • mouseover’ / ‘mouseout’ – mouse-over
  • moveend’, ‘zoomend’ – end of move or zoom operation

Slide 2: Map events

Map events (or global events) concern the entire map and are often used to capture actions such as view changes, zooming or interactions with the map.

a. zoom and zoomend

  • -zoom: This event is triggered whenever the map’s zoom level changes, whether due to manual or programmatic zoom.
  • -zoomend : This event is triggered once zooming is complete.

b. move and moveend

  • -move: This event is triggered every time the map is moved (when the map view changes).
  • -moveend : This event is triggered when map movement is complete.

c. click

  • -click: This event is triggered when the user clicks on the map (in any area of the map).

d. dblclick

  • -dblclick: This event is triggered when a user double-clicks on the map. This can be used to zoom in, for example.

Slide 3: Layer events

Layer-specific events capture interactions with elements such as markers, polygons or circles.

a. add and remove

  • -add: This event is triggered when a layer is added to the map.
  • -remove: This event is triggered when a layer is removed from the map.

b. click on a layer

  • -click: When a user clicks on a specific layer element, such as a marker, polygon or circle, this event is triggered.

c. mouseover and mouseout

  • -mouseover: This event is triggered when the user hovers over an element with the mouse (such as a marker, polygon or line).
  • -mouseout: This event is triggered when the user leaves an element with the mouse.

d. drag and dragend

  • -drag: This event is triggered when the user drags an element (such as a marker) across the map.
  • -dragend : This event is triggered when an element that has been dragged stops.

Slide 4: Geometry events (for geospatial data objects)

Events linked to geospatial objects such as polygons, lines and circles capture actions such as drawing, modifying or deleting geometries.

a. create (for drawings)

  • create: This event is triggered after a user has created a new geometry, such as a polygon or circle, using a drawing tool.

Example :

var drawnItems = new L.FeatureGroup();

map.addLayer(drawnItems);

 

var drawControl = new L.Control.Draw({

  edit: { featureGroup: drawnItems }

});

 

map.addControl(drawControl);

 

map.on('draw:created', function(e) {

  console.log("Une nouvelle géométrie a été créée : ", e.layer);

  drawnItems.addLayer(e.layer);

});

b. edit (for geometry modification)

  • edit: This event is triggered when the user modifies existing geometry (such as a polygon or line).

Example:

map.on('draw:edited', function(e) {

  console.log("Les géométries ont été modifiées : ", e.layers);

});

Slide 5: Attaching an event to a marker in Leaflet

In Leaflet, markers are interactive geographic objects that you can place on the map. You can easily attach events to these markers to capture user actions, such as a click, mouse-over or move.

Here’s how to attach common events to a marker:

1.Creating a marker

Before attaching events, you must first create a marker. This is done with the L.marker() function, specifying the geographic coordinates where you wish to place it on the map.

Example:

var map = L.map('map').setView([48.8566, 2.3522], 13); // Positionner la carte sur Paris

// Créer un marqueur sur Paris

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


2.Attaching a click event

The click event is one of the most common events attached to markers. It is triggered every time a user clicks on a marker. You can use this event to display a popup, record an action or trigger a specific function.

Example

marker.on('click', function() {

  console.log('Vous avez cliqué sur le marqueur.');

  marker.bindPopup('C\'est un marqueur à Paris !').openPopup(); // Afficher un popup

});

Explanation:

  • on(‘click’, …): Attaches a click event to the marker.
  • bindPopup(‘…’): Adds a popup to the marker.
  • openPopup() : Opens the popup when a click is detected.

Slide 6 : Attaching mouseover and mouseout events

The mouseover and mouseout events are triggered when the mouse hovers over the marker and when the mouse leaves the marker, respectively. These events are often used to create interactive visual effects, such as changing the color or size of the marker.

Example:

marker.on('mouseover', function() {

  console.log('La souris est sur le marqueur.');

  marker.setIcon(L.icon({

    iconUrl: 'path/to/hover-icon.png',

    iconSize: [32, 32],

  })); // Modifier l'icône du marqueur au survol

});

marker.on('mouseout', function() {

  console.log('La souris a quitté le marqueur.');

  marker.setIcon(L.icon({

    iconUrl: 'path/to/default-icon.png',

    iconSize: [32, 32],

  })); // Restaurer l'icône par défaut

});

EExplanation:

  • setIcon(): Changes the marker icon.
  • The icon is changed on hover and restored when the marker is left.

Slide 7: Attaching a drag and dragend event (for a draggable marker)

You can make a marker draggable and attach events to the marker’s movement. The drag event is triggered while the marker is being moved, and dragend when the move is complete.

Example::

marker.dragging.enable(); // Activer le déplacement du marqueur

marker.on('drag', function() {

  console.log('Le marqueur est en train d\'être déplacé.');

});

marker.on('dragend', function() {

  console.log('Le marqueur a été déplacé.');

  console.log('Nouvelle position : ' + marker.getLatLng()); // Affiche les nouvelles coordonnées

});

Explanation:

  • dragging.enable(): Enables the marker to be dragged.
  • getLatLng(): Retrieves the marker’s new coordinates after dragging.

Slide 8: Attaching a contextmenu event (right-click)

The contextmenu event is triggered when a marker is right-clicked. This can be useful for displaying a context menu or executing a specific action when the user right-clicks.

Example:

marker.on('contextmenu', function(e) {

  console.log('Clic droit détecté sur le marqueur.');

  alert('Clic droit effectué à : ' + e.latlng); // Affiche un message avec les coordonnées du clic

});

Explanation:

  • e.latlng : Contains the coordinates where the right click took place.

Slide 9: Attaching a dblclick event (double-click)

The dblclick event is triggered when a user double-clicks on a marker. You can use it to perform specific actions on a double-click, such as zooming in on the map or modifying marker properties.

Example:

marker.on('dblclick', function() {

  console.log('Double-clic sur le marqueur détecté.');

  map.setView(marker.getLatLng(), 16); // Zoomer sur le marqueur après un double-clic

});

Explanation:

  • map.setView(): Changes the map view to center the map on the marker and zoom in.

Slide 10: Attaching a dragstart event (at the start of a move)

The dragstart event is triggered right at the start of a marker move, which can be useful for animations or adjustments before the marker is moved.

Example:

marker.on('dragstart', function() {

  console.log('Le déplacement du marqueur a commencé.');

});


Slide 11 : Click on map → display coordinates

You can display the coordinates where the user clicks. This is very useful for locating a point.

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

    alert(“Vous avez cliqué à :\nLatitude : ” + e.latlng.lat.toFixed(5) +

           “\nLongitude : ” + e.latlng.lng.toFixed(5));

});

Or, better still, to place a marker there.

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

    L.marker(e.latlng).addTo(map)

     .bindPopup(“Nouveau point :<br>” + e.latlng.toString())

     .openPopup();});

Slide 12 : Interactive popup form (add a comment)

You can display a form in a popup so that the user can enter information.

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

    var popup = L.popup()

        .setLatLng(e.latlng)

        .setContent(‘<b>Ajouter un commentaire :</b><br><input type=”text« 

        id=”inputComment” /><br><button onclick=”saveComment()”>Envoyer</button>’)
        .openOn(map);

   window.saveComment = function() {

        var text = document.getElementById(“inputComment”).value;

        alert(“Commentaire enregistré : ” + text);

        map.closePopup();    };});

Slide 13 : Zoom or move detection

Very useful for dynamically updating visible data (e.g. loading data according to zone).

map.on(‘moveend zoomend’, function() {

    console.log(“Vue actuelle :”, map.getBounds());     console.log(“Niveau de zoom :”, map.getZoom());});

Slide 14 : Update element on hover

You can dynamically change the style of an object (GeoJSON, polygon…) when the mouse hovers over it.

L.geoJSON(zone, {

    style: { color: “green”, weight: 2 },

    onEachFeature: function (feature, layer) {

        layer.on({

            mouseover: function(e) {

                e.target.setStyle({ color: “red” });

            },

            mouseout: function(e) {

                e.target.setStyle({ color: “green” });

            }

        });

    }}).addTo(map);

Slide 15: Dynamically modifying an object in Leaflet

Dynamically modifying an object means changing its properties or appearance in response to a user action (click, hover, zoom, etc.). This makes maps interactive, intuitive and easier to read.

Why dynamically modify an object?

Reacting to user actions

For example, when the user hovers over an area, you can :

  • change the color of the polygon,
  • display a temporary tooltip,
  • enlarge a marker.

Refresh content or style in real time

You can :

  • update popup data (e.g. live temperature),
  • change a marker icon according to an event (alert, weather, etc.),
  • adapt the style of a plot according to a zoom.

Improve legibility and user experience

A visually changing object draws attention :

  • important elements,
  • to possible interactions.

Examples of dynamic modifications

// Survol : changer le style d’un polygone
layer.on('mouseover', function () {
  this.setStyle({
    fillColor: 'yellow',
    color: 'orange'
  });
});

// Clic : changer l’icône d’un marqueur
marker.on('click', function () {
  this.setIcon(newIcon);
});

// Double clic : modifier un texte de popup
marker.on('dblclick', function () {
  this.bindPopup("Texte mis à jour").openPopup();
});

Things to remember

Dynamically modifying an object brings the map to life: it responds, informs and guides. It transforms a simple background map into a truly interactive interface.

Slide 16: Dynamically modifying an object over time

In Leaflet, objects can be modified automatically, without user interaction, using time as a trigger.

This makes it possible to :

  • visually animate a map,
  • draw attention to an element,
  • represent an evolution (e.g. simulation or displacement).

Why change an object over time?

  1. Signal an alert or danger zone (flashing, color change)
  2. Show an evolution over time (e.g. vehicle movement, temperature variation)
  3. Create visual effects to enhance the interface (pulsing, alternating icons)

Example: a flashing polygon

Its color alternates every 500 milliseconds..

let isRed = true;

setInterval(() => {
  polygon.setStyle({
    color: isRed ? 'red' : 'orange',
    fillColor: isRed ? 'red' : 'orange'
  });
  isRed = !isRed;
}, 500);

Example: moving a marker every second

let lat = -19.7, lng = 63.4;
const marker = L.marker([lat, lng]).addTo(map);

setInterval(() => {
  lat += 0.0005;
  marker.setLatLng([lat, lng]);
}, 1000);

Things to remember

With pure JavaScript, Leaflet can bring the map to life even without interaction. This provides a dynamic dimension.


Slide 17 : Dynamically modify an object via user selection

In an interactive map application, it is often useful to allow the user to modify the appearance of objects displayed on the map. Leaflet, combined with HTML and JavaScript, easily enables this type of interaction.

Objective

  • Enable the user to customize the display of an object (e.g. a polygon) according to a value chosen in an HTML interface (e.g. drop-down menu). This improves :
  • Data accessibility and comprehension
  • Map interactivity
  • User experience (UX)

Use case: Choosing the color of a polygon

A polygon is displayed on the map, representing, for example, a protected area. An HTML menu allows the user to choose a color. When a new color is selected, the polygon style is dynamically updated.

Code example (simplified extract)

<select id="colorSelect">
  <option value="blue">Bleu</option>
  <option value="green">Vert</option>
  <option value="red">Rouge</option>
</select>

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

<script>
  const map = L.map('map').setView([48.85, 2.35], 12); // Exemple : Paris

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

  // Exemple de polygone
  const polygon = L.polygon([
    [48.85, 2.35],
    [48.86, 2.36],
    [48.85, 2.37]
  ], {
    color: 'blue'
  }).addTo(map);

  // Mise à jour du style selon la sélection
  document.getElementById('colorSelect').addEventListener('change', (e) => {
    const newColor = e.target.value;
    polygon.setStyle({ color: newColor });
  });
</script>

To remember

  • The menu change event is triggered each time a modification is made.
  • Leaflet’s .setStyle() method dynamically changes the style of a polygon, line or circle.
  • This principle can be extended to other styles: thickness (weight), opacity (opacity), fill (fillColor), etc.


Conclusion

Attaching events to markers in Leaflet is essential for adding interactivity to the map. Events such as click, mouseover, drag and contextmenu allow you to react to user actions and dynamically modify the state or content of your map. Using events on markers makes the map more dynamic and enables you to create more engaging and personalized user experiences.


Practical exercise – Creation of an interactive tourist map

Objective

To create an interactive map of a tourist destination (city, park, trail, etc.) in which :

  • points of interest are displayed with information when clicked,
  • the color of a polygon changes when hovering the mouse over it,
  • a mobile pop-up window shows the coordinates of the click on the map,
  • a click counter in the upper left corner,
  • a button to reset the map.

Supplied items

You will find these items in the directory …\leaflet_starter_kit_data

  • A points.geojson file containing 3-4 POIs with name and description properties
  • A polygon representing an area (zone.geojson)

Instructions

  1. View the map centered on the area of interest at the appropriate zoom level.
  2. Add points of interest (points.geojson):

    • Display a custom icon for markers.
    • Add a popup window on click with name and description.
    • Change the hover icon (mouseover / mouseout)

  3. Display a zone (zone.geojson):

    • Apply a basic style
    • Change the background color on mouse over
    • Restore the original style when the mouse leaves the zone

  4. Add an event to the whole map

    • When the user clicks on the map, a moving popup window opens at the click location with lat/lon coordinates
    • Displays a click counter in a div (#counter) that updates with each click.

  5. Adds a “Reset” button:

    • Resets the map to its initial state (view and counter).

Bonus (optional)

  • Displays a mini-map or scale
  • Adds a fixed tooltip with instructions

Warning: If you can’t see the geojson layers on your map

Diagnosis: open the HTML file directly from disk (file://)

When you do this, the browser often blocks fetch(‘rando1.geojson’) requests for security reasons.

Simple solution: use a small local server

Here’s how to do it very easily with Python (no need to program anything):

1. Open a terminal window in the folder containing index.html and the geojson files.

2. Type (depending on Python version) :

# If Python 3

python -m http.server 8000

3. Open your browser and go to :

http://localhost:8000

Loading with fetch() will now work without a hitch!


View the solution in a new tab

(We recommend that you complete the exercise on your own before consulting the answers).

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 *