[GIS] how does one reset map.fitbounds (zoomtofeature()) to the original zoom

eventsleafletmapbox

I have a lovely map setup using Leaflet with MapBox tiles (only). It is a United States map with polygons for each state with an onclick event to zoomToFeature.

The basic zoomToFeature() function from the tutorials does exactly what I want on the way in, but is there a similarly easy way to zoom out to original zoom?

I guess I could set a global variable to hold the state on the first event, and do an if inside zoomToFeature to either zoom or pull back, I just wonder if there is already some code that does this more elegantly.

Specifically for it to zoom out to exactly where the map was. Not only to the original zoom level, but also the original center.

Best Answer

var extentControl = L.Control.extend({
options: {
    position: 'topleft'
},
onAdd: function (map) {
    var llBounds = map.getBounds();
    var container = L.DomUtil.create('div', 'extentControl');
    $(container).css('background', 'url(i/extent.png) no-repeat 50% 50%').css('width', '26px').css('height', '26px').css('outline', '1px black');
    $(container).on('click', function () {
        map.fitBounds(llBounds);
    });
    return container;
   }
})

map.addControl(new extentControl());

This works pretty simple. The custom button sets the llBounds variable when added to the map (on load), which is then called when the button is clicked. Customize with your own extent image and whatever else you'd like style wise.