Skip to content

Instantly share code, notes, and snippets.

@aerispaha
Created October 2, 2018 22:30
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save aerispaha/826a9f2fbbdf37983dc01e6074ce7cd7 to your computer and use it in GitHub Desktop.
Save aerispaha/826a9f2fbbdf37983dc01e6074ce7cd7 to your computer and use it in GitHub Desktop.
Zoom to Feature in MapBox Map
var zoomToFeat = function(feature, map) {
// based on this: https://www.mapbox.com/mapbox-gl-js/example/zoomto-linestring/
// Geographic coordinates of the LineString
var coordinates = feature.geometry.coordinates;
// Pass the first coordinates in the LineString to `lngLatBounds` &
// wrap each coordinate pair in `extend` to include them in the bounds
// result. A variation of this technique could be applied to zooming
// to the bounds of multiple Points or Polygon geomteries - it just
// requires wrapping all the coordinates with the extend method.
var bounds = coordinates.reduce(function(bounds, coord) {
return bounds.extend(coord);
}, new mapboxgl.LngLatBounds(coordinates[0], coordinates[0]));
map.fitBounds(bounds, {
padding: 20
});
};
@chriszrc
Copy link

chriszrc commented Aug 3, 2021

It's surprising mapbox doesn't have a bbox method yet, I usually use https://turfjs.org/docs/#bbox to achieve the above, but for now, it does seem like that's the way to do it without external libs-

@cwhite92
Copy link

Thank you!!

Changed it ever so slightly to work with polygons:

                let coordinates = e.features[0].geometry.coordinates[0];
                let bounds = coordinates.reduce(function(bounds, coord) {
                    return bounds.extend(coord);
                }, new mapboxgl.LngLatBounds(coordinates[0], coordinates[0]));

@aerispaha
Copy link
Author

Awesome, thanks @cwhite92!

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment