Zoom-in on a single cluster of points with OpenLayers

Viewed 120

I've many points rendered as cluster using ol.source.Cluster. I need to zoom-in on a single cluster extentions and I'm trying to do this using below code:

map.on('singleclick', event => {
 extent = feature.getGeometry().getExtent();
 options = {
   size: map.getSize(),
   padding: [50, 50, 50, 50],
   duration: 1000
 }
 map.getView().fit(extent, options);
})

When the point is unclustered and I click on it I can see correctly it at the center of the map and the scale line move from 2000km to 50mm; but when I've a cluster of points, when I click on the cluster, I see that the scale line move from 2000km to 50mm and I can't see the points.

How I can solve it?

1 Answers

The geometry of the cluster is a single point where the cluster is shown. When you zoom in the cluster will be expanded to individual features, so you should use the extent of those:

import (createEmpty, extend} from 'ol/extent'

...

extent = createEmpty();
feature.get('features').forEach(function(feature){
  extend(extent, feature.getGeometry().getExtent());
});
...
map.getView().fit(extent, options);
Related