Maybe it is a stupid question but anyway,
On the search page in my application, I have a range input that determines search range (min 5 km, max 50 km.). Depending on set value, I'd like to change current zoom in MapBox GL map so that it displays only the area that has been set in this input (if search range is about 10 km., I should see only a map sector with a radius of 10 km.). I'm a bit weak at math, which prevents me to find this correlation.
Thanks in advance.
So you want the map area to encompass a circle of a size specified in kilometres.
One simple (but slightly bloaty) way to do this would be using Turf.
const rangeCircle) = turf.circle(map.getCenter().toArray(), radius, { units: 'kilometers' });
map.fitBounds(turf.bbox(rangeCircle))
That way you don't need to explicitly compute the zoom level - Mapbox's fitBounds() will figure that out for you.
Finally I figured out how to do that using Turf.js. Here is my solution:
function fitToRadius(radius) {
const { lng, lat } = mapbox.getCenter();
const center = [lng, lat];
const rangeCircle = turf.circle(
center,
radius,
{ units: "kilometers"}
);
const [coordinates] = rangeCircle.geometry.coordinates;
const bounds = new mapboxgl.LngLatBounds(
coordinates[0],
coordinates[0]
);
/* Extend the 'LngLatBounds'
to include every coordinate in the bounds result. */
coordinates.forEach((coord) => bounds.extend(coord));
mapbox.fitBounds(bounds);
}
Thanks to Steve Bennett for his hint about Turf.js.