map.fitBounds doesn't work properly with center argument
Nobody has claimed this yet.
- Dominant language
- TypeScript
- Stars
- 12.4k
- Forks
- 2.4k
- PR merge metrics
- No merged PRs in 30d
Description
**mapbox-gl-js version**: 3.12
**browser**: not important
When providing center to `map.fitBounds` it doesn't' work as expected - that is showing the bounds inside view but with camera at `center`
I need to workaround it like that:
```ts
if (center) {
let maxDistanceFromCenter = 0;
poisToFit.forEach(poi => {
const distance = getDistanceFrom(poi, { latitude: center[1], longitude: center[0] });
if (distance > maxDistanceFromCenter) {
maxDistanceFromCenter = distance;
}
});
const centerPoint = turf.point(center);
const directions = [0, 90, 180, 270]; // North, East, South, West
const bounds = new mapboxgl.LngLatBounds([center[0], center[1]], [center[0], center[1]]);
directions.forEach(bearing => {
const dest = turf.destination(centerPoint, maxDistanceFromCenter, bearing, { units: "meters" });
const [lng, lat] = dest.geometry.coordinates;
bounds.extend([lng, lat]);
});
const options: mapboxgl.EasingOptions = defined({
padding,
animate: true,
duration: 1000,
});
map.fitBounds(bounds, options);
}
```
While I would prefer to have something like this:
```ts
map.fitBounds(bounds, {
padding,
animate: true,
duration: 1000,
center: center ? { lng: center[0], lat: center[1] } : undefined,
});
```
I also spotted that this api doesn't work well when passing undefined so that's why use of `defined` by me (removes undefined values from object)
Contributor guide
First steps
- Read the whole issue, then the project's contributing guide.
- Comment on the issue to say you are picking it up — it saves two people doing the same work.
- Fork the repository and make your change on a branch.
- Open a pull request that references the issue number.
Research direction
Start at the map.fitBounds API and compare its documented options with the reported center behavior. Reproduce the example using mapbox-gl-js 3.12 with bounds, center, padding, and animation; done means the requested center is honored while the bounds remain visible, with a regression test if the project provides one.
Written by the indexing model from the issue text.
Assessment
- Tech stack
- javascript, typescript
- Domain
- api, frontend
- Issue type
- Bug
- Difficulty
- 5/5
- Estimated time
- Over a week
- Activity status
- Stale
- Clarity
- Mostly clear
- Newbie friendliness
- 32/100