I'm trying to zoom to a clicked cluster in OpenLayers in order to show polygons in that cluster.
const zoomToCluster = (cluster: Feature) => {
const features = cluster.get('features')
const extent = boundingExtent(
features.map((f: any) => f.getGeometry().getFlatCoordinates())
)
viewRef.current.fit(extent,
{duration: 1000, padding: [200, 200, 200, 200]}
)
}
I did this similarly to an official example:
map.on('click', (e) => {
clusters.getFeatures(e.pixel).then((clickedFeatures) => {
if (clickedFeatures.length) {
// Get clustered Coordinates
const features = clickedFeatures[0].get('features');
if (features.length > 1) {
const extent = boundingExtent(
features.map((r) => r.getGeometry().getCoordinates()),
);
map.getView().fit(extent, {duration: 1000, padding: [50, 50, 50, 50]});
}
}
});
});
The problem is that clicking on a cluster with a single polygon will make boundingExtent return a point-sized extent instead of the expected extent around the polygon.
I have checked and getCoordinates() returns the correct coordinates of my polygon, but the result is an array of pairs, so I used getFlatCoordinates() instead.