1

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.

2
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.

  • well, i don't want to add another control to the map though. when i zoom/pan over into a state onclick i want to be able to click the same state polygon a second time to return to the initial positions. – vaxhax Feb 21 '14 at 5:00
  • One approach would be to still create a llBounds variable on map load, and also create a binary variable, such as var zoomed = false. Inside of the zoomToFeature function, create an if conditional that checks the zoomed variable. If false, map.fitBounds(e.target.getBounds()) (like in the example) and set zoomed = true. If true, map.fitBounds(llBounds) and set zoomed = false. – evv_gis Feb 21 '14 at 15:01
0

You could use the following:

map.fitBounds(x.getBounds());  //where x is the name of your layer where all the polygons are located

This is modified from an example on the Leaflet reference.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Not the answer you're looking for? Browse other questions tagged or ask your own question.