In my map, there are various features with IDs stored in an array called featureIds
.
Within my application, I have a button that can toggle the visibility of certain features.
To address this toggling behavior, I am developing a JavaScript function named reCenter()
. This function adjusts the map view to fit the bounds of only the visible features.
function reCenter() {
// initialize new array for visible features
var visibleFeatures = [];
// identify and add visible features to the new array
for (var i = 0; i < featureIds.length; i++) {
if (map.getLayoutProperty(featureIds[i], "visibility") == "visible") {
visibleFeatures.push(map.queryRenderedFeatures(featureIds[i]));
}
}
// set up array to store coordinates
var coordinates = [];
// gather coordinates for each visible feature and add them to the array
for (var j = 0; j < visibleFeatures.length; j++) {
coordinates.push(coord.geometry.coordinates);
}
// adjust map view as described 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 following the instructions at https://docs.mapbox.com/mapbox-gl-js/example/zoomto-linestring/, I encounter the error: TypeError: this._sw is undefined
What is the most effective way to dynamically retrieve all coordinates of visible features and pass them into map.fitBounds()
?