Mapbox GL JS getBounds()/fitBounds()

前端 未结 5 1676
自闭症患者
自闭症患者 2020-12-13 17:44

I\'m using Mapbox GL JS v0.14.2 and I\'ve searched high and low through the documentation and very little is clear about this.

If you use the standard JS API, it\'s

5条回答
  •  感动是毒
    2020-12-13 18:10

    This is my solution based on the reduce operation from a Mapbox example.

    It works for geojson that contain point features and multi-point features like lines.

    let bounds = geoJSON.features.reduce(function(bounds, feature) {
      if(!Array.isArray(feature.geometry.coordinates[0])) { // point feature
        return bounds.extend(feature.geometry.coordinates);
      } else {
        return feature.geometry.coordinates.reduce(function(bounds, coord) {
          return bounds.extend(coord);
        }, bounds);
      }
    }, new mapboxgl.LngLatBounds());
    
    map.fitBounds(bounds, {
      maxZoom: 12,
      padding: 30, // in px, to make markers on the top edge visible
    })
    

提交回复
热议问题