0

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.

1 Answer 1

0

This is not an actual solution, but a workaround. I managed to get it working by simply not using boundingExtent() when I have a single polygon in a cluster:

const zoomToCluster = (cluster: Feature) => {
  const features = cluster.get('features')
  let extent: number[] = []

  if (features.length > 1) {
    extent = boundingExtent(
      features.map((f: any) => f.getGeometry().getFlatCoordinates())
    )
  } else if (features.length === 1) {
    extent = features[0].getGeometry().getExtent()
  }

  viewRef.current.fit(extent,
    {duration: 1000, padding: [200, 200, 200, 200]}
  )
}
Sign up to request clarification or add additional context in comments.

Comments

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.