How to add a reset zoom button to a Leaflet map

Note: This post assumes that you already have a Leaflet map set up and are thus, naturally, familiar with the basics of web development.

Why I make this?

Leaflet is fantastic. But as with a lot of open-source projects, it lacks a few features that you might be commonsense for you.

For me, that feature was a reset zoom button.

The house takes you home

How to do this?

Simply add this code snippet to the JavaScript file where you’re initializing your Leaflet map. Or abstract the code into a separate file and import it.

You could even save the function’s output in a variable and add it to the map later, if that’s your style.

 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
15
16
17
(function() {
  var control = new L.Control({position:'topleft'});
  control.onAdd = function(map) {
      var azoom = L.DomUtil.create('a','mt-0');
      azoom.innerHTML = '<div class="leaflet-control-zoom leaflet-bar leaflet-control mt-0 ms-0"><a class="leaflet-control-reset-zoom" title="Reset zoom" role="button" aria-label="Reset zoom">
      <svg xmlns="http://www.w3.org/2000/svg" width="16" height="16" fill="currentColor" class="bi bi-house" viewBox="0 0 16 16"><path fill-rule="evenodd" d="M2 13.5V7h1v6.5a.5.5 0 0 0 .5.5h9a.5.5 0 0 0 .5-.5V7h1v6.5a1.5 1.5 0 0 1-1.5 1.5h-9A1.5 1.5 0 0 1 2 13.5zm11-11V6l-2-2V2.5a.5.5 0 0 1 .5-.5h1a.5.5 0 0 1 .5.5z"/><path fill-rule="evenodd" d="M7.293 1.5a1 1 0 0 1 1.414 0l6.647 6.646a.5.5 0 0 1-.708.708L8 2.207 1.354 8.854a.5.5 0 1 1-.708-.708L7.293 1.5z"/></svg>
      </a></div>';
      L.DomEvent
        .disableClickPropagation(azoom)
        .addListener(azoom, 'click', function() {
          map.setView(map.options.center, map.options.zoom);
        },azoom);
      return azoom;
    };
  return control;
}())
.addTo(map);

Add these styles manually if you’re not using Bootstrap 5.0 –

1
2
3
4
5
6
mt-0 {
  margin-top: 0px;
}
ms-0 {
  margin-left: 0px;
}

There you go. Enjoy your on the map.