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()
?