What ended up working is calculating the new latitude, longitude, and zoom for my new extent I was zooming to using WebMercatorViewport, and then set that as the new viewport state. I used the FlyToInterpolator method that react-map-gl offers to fly to that location.
const {longitude, latitude, zoom } = new WebMercatorViewport(this.state.viewport)
.fitBounds([[extent[0], extent[1]], [extent[2], extent[3]]], {padding: {top: 82, bottom: 30, left: leftPadding, right: 30}});
const viewport = {
...this.state.viewport,
longitude,
latitude,
zoom,
transitionDuration: 2000,
transitionInterpolator: new FlyToInterpolator()
}
this.setState({viewport});
Answer from dugtoni on Stack OverflowThe input am passing to fitBounds should be in the form of Array<Array<number>>
getMinOrMax(markersObj, minOrMax, latOrLng) {
if(minOrMax == "max"){
return _.maxBy(markersObj, function (value) {
return value[latOrLng]
})[latOrLng];
}else{
return _.minBy(markersObj, function (value) {
return value[latOrLng]
})[latOrLng];
}
}
getBounds(markersObj) {
var maxLat = this.getMinOrMax(markersObj, "max", "lat");
var minLat = this.getMinOrMax(markersObj, "min", "lat");
var maxLng = this.getMinOrMax(markersObj, "max", "lng");
var minLng = this.getMinOrMax(markersObj, "min", "lng");
var southWest = [minLng, minLat];
var northEast = [maxLng, maxLat];
return [southWest, northEast];
}
So am using the above methods to find figure out SouthWest and NorthEast points from the given array of marker position objects.
Marker sample objects should to be like below:
var markerPoints = [{lng:12.49637,lat:41.90278},{lng:12.319398,lat:45.441906},{lng:13.055054,lat:47.809532},{lng:16.373724,lat:48.208244}]
<Map
style="mapbox://styles/mapbox/streets-v9"
containerStyle={{
height: "100%",
width: "100%"
}}
fitBounds={this.getBounds(markerPoints)}>
<markers />
</Map>
Note: Am using lodash liblary for utility functions like min and max in the example.
Thanks,
Josan
You are passing the wrong bounds format to the fitBounds() function.
Fit bounds expects as an argument: fitBounds : Array<Array<number>>
See the docs: https://github.com/alex3165/react-mapbox-gl/blob/master/docs/API.md
In mapbox this is called an "LngLatBoundsLike Object", see here: https://www.mapbox.com/mapbox-gl-js/api/#lnglatlike
So your function call must be something like this:
fitBounds([[12.49637,41.90278],[12.319398,45.441906]]);
Where the first argument is the southwest corner and the second argument is the northeast corner of your desired bounding box