This course will become read-only in the near future. Tell us at if that is a problem.

Events: listening to your users


---This section shows how to detect and respond to your users moving and zooming the map---

In programming-speak, an event is generated whenever the user moves the mouse, clicks, types a key, or does other actions, such as moving and zooming a map.  Event listeners detect and respond to these events.  A good example is how Leaflet.js will open a popup window when you click on a marker.

Suppose we want a map which changes when the user zooms out. We need to create an event listener, so that our code will respond when the user changes the zoom.  Use the reference at to research the event type which we should look for.  Under EVENT_TYPES, the map object has an event called zoomend.

We connect the Leaflet map's zoomend event by adding something like this after your map is created. It will replace the map with "you zoomed the map!" after you change the zoom.

map.on( "zoomend", function( e ) {
    // runs this code after you finishing the zoom
   document.getElementById("mymap").innerHTML "you zoomed the map!";


To make this event listener useful, we need to have it act on the map.  You probably want to know what the new zoom level is, so we will need to call map.getZoom() to see that.  Change the function to this:

map.on( "zoomend", function( e ) {
    console.log( "zoom level is " + map.getZoom() )

Run this, go to your browser's JavaScript console, and you'll see the zoom level numbers. You'll notice that zooming in increases this zoom number, and zooming out subtracts. There are only integer zoom levels.


For my next example, I've decided that if your zoom level becomes 3 or lower ( even more zoomed out ), I will remove the marker from the map.

map.on( "zoomend", function( e ) {
    zoom = map.getZoom( );
    if ( zoom <= 3 ) {
        map.removeLayer( marker );


Also you can go back to this example from earlier:

marker = new L.Marker( latlng );
marker.bindPopup('Pop up on the map!');



This makes it so that you don't have to click a marker for its popup to appear - you can just move the mouse over it and trigger the mouseover event.


You can research other events, such as moveend , to redraw parts of your map and load more information when the user moves to a new area.  Many websites use this event so that the page's sidebar will only show information about places which are visible on your map ( is a great example of this for restaurant search ).  You could also use this to keep users from moving the map too much and losing the site which you've mapped.

Task Discussion