0

I'm creating a map where severals polygons are showed and I want to center/autozoom the map according to the showed polygons.

To make it happens I've created a bounds object that I'll extends with the bounds of each polygons like so:

private readonly bounds = new mapboxgl.LngLatBounds();

myFunction() {
  this.polygons.forEach((polygon) => {
    const source = this.map.addSource(polygon.key, {
      type: 'geojson',
      data: polygon.geometry,
    });

    this.bounds.extend(source.getBounds());
  })
  
  this.map.fitBounds(this.bounds, {
    padding: 20,
  });
}

But the map keep the same level of zoom and the view is not well centered. Why?

Edit: I've added a marker in the north east and in the south west of the bounds property and they are not corresponding to the actual showed polygons. How to get the actual bounds of my polygons?

Splinteer
  • 1,126
  • 4
  • 13
  • 28

1 Answers1

0

As I understand your problem, you will need to define a bbox object and pass it to you map with function .fitBounds See example https://docs.mapbox.com/mapbox-gl-js/example/fitbounds/

To calculate the bbox according the size of the area you will need turf library, or if the object is in DB the best approach is to use Postgis extention