ChipnCharge
ChipnCharge

Reputation: 538

Mapbox: Zooming Out One Level After Using fitBounds Re-Centers Map

I am using Mapbox GL JS and created a dynamic store locator based on their store locator demo. I am using fitBounds to include all store markers on the initial display of the map.

The problem is, it zooms in too close and the map needs a bit of padding. So, I'm trying to back out the zoom one level. The problem is, when I get the zoom level and back out one, the map is recentered to the original center of the map.

I have included code below where I try to reset the center to the fitBounds center but it's not working. Any idea what I'm doing wrong?

var bounds = new mapboxgl.LngLatBounds();
$(markers).each(function() {
    var features = $(this);
    bounds.extend(features[0].geometry.coordinates);        
});

map.fitBounds(bounds);
var mapLat = map.getBounds().getCenter().lat;
var mapLong = map.getBounds().getCenter().long;
map.setCenter = (mapLat, mapLong);
var mapZoom = map.getZoom();
newZoom = mapZoom - 1;  
map.setZoom(newZoom); 

Upvotes: 5

Views: 10091

Answers (1)

Scarysize
Scarysize

Reputation: 4281

If all you want to achieve is to add padding to the bounds, mapbox-gl provides an option for this in fitBounds:

map.fitBounds(bounds, {padding: 100}) // adds 100px padding to the bounds

Here is the documentation: https://www.mapbox.com/mapbox-gl-js/api#map#fitbounds

Upvotes: 14

Related Questions