0

My map contains multiple features, the ids for all these features are stored in an array: featureIds.

My application contains a button which toggles the visibililty of some of the features.

I am working on a JavaScript function reCenter() to follow this toggling. This function "zooms" out and refits the map view in accordance to the bounds of features which are now visible.

function reCenter() {

// new array for visible features 
var visibleFeatures = [];

// retrieve the features which are visible and put them into the new array
    for (var i = 0; i < featureIds.length; i++) {

        if (map.getLayoutProperty(featureIds[i], "visibility") == "visible") {

            visibleFeatures.push(map.queryRenderedFeatures(featureIds[i]));
        }

    }

    // new array to store coordinates
    coordinates = [];


    // push coordinates for each visible feature to coordinates array    
    for (var j = 0; j < visibleFeatures.length; j++) {

        coordinates.push(coord.geometry.coordinates);

    }

    // do fit as shown here : https://docs.mapbox.com/mapbox-gl-js/example/zoomto-linestring/
    var bounds = coordinates.reduce(function (bounds, coord) {
        return bounds.extend(coord);
    }, new mapboxgl.LngLatBounds(coordinates[0], coordinates[0]));

    map.fitBounds(bounds, {
        padding: 20
    });
}

Despite implementing the above and following the guidance provided at https://docs.mapbox.com/mapbox-gl-js/example/zoomto-linestring/. I receive the following error: TypeError: this._sw is undefined

How can one best dyanmically retrieve all coordinates of visibile features and pass them into map.fitBounds()?

Scribbio
  • 113
  • 10

2 Answers2

1

Try Turf.js: js is an open-source JavaScript library used for spatial analysis.

And it provide's a method bbox (http://turfjs.org/docs/#bbox)

It take's some set of feature's and will automatically calculate bbox for you. and set that final bbox to fitbounds.

and there's a similar question asked earlier: Mapbox GL JS getBounds()/fitBounds()

Dolly
  • 2,213
  • 16
  • 38
1

Get all your features and create a FeatureCollection and with bbox function from Turf.js get the bounds of the FeatureCollection. here is how I do that: note: use toWgs84 if your coordinates are not wgs84.

const features = [
    {
         type: 'Feature',
         geometry: {
             type: 'Polygon',
             coordinates: [
                 [your_feature_s_coordinates],
                 [...],
             ]
         }
     },
     {another feature}
 ]

 const FeatureCollection = {
     type: "FeatureCollection",
     features: features
 };

 map.fitBounds(bbox(toWgs84(FeatureCollection)));
ahmetkilinc
  • 674
  • 7
  • 19