mapbox / mapbox/mapbox-gl-js

map.fitBounds doesn't work properly with center argument

Open
#13,483 3 comments 0 reactions 0 assignees View on GitHub

Nobody has claimed this yet.

needs information :pray:
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

Open the contributing guide

First steps

  1. Read the whole issue, then the project's contributing guide.
  2. Comment on the issue to say you are picking it up — it saves two people doing the same work.
  3. Fork the repository and make your change on a branch.
  4. 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

Get new issues in your inbox

A short digest of beginner-friendly GitHub issues.