[GIS] Rotating current map extent around center point in OpenLayers

extentsopenlayers

What would be the best way to take current extent and rotate it for 90 degrees around center point and it would work for any projection.

Let's say I have a map with n-layers enabled and landscape view. Meaning I can get extent of it. How can I get extent of a rotated view (90° rotation).
Sketch of rotation:
illustration of desired effect
_

Center is fixed and should stay the same and aspect ration should be same as before.

Best Answer

This should do it:

  const get_rotated_extent = (map, degrees) => {
    const view = map.getView()
    const extent = view.calculateExtent(map.getSize())
    const geom = ol.geom.Polygon.fromExtent(extent)
    const map_center = view.getCenter()
    const rotation_in_radians = degrees * Math.PI / 180
    geom.rotate(rotation_in_radians, map_center) 
    return geom.getExtent()
  }
  const rotated_extent = get_rotated_extent(map, 90)

To test it visually:

  const polygon_source = new ol.source.Vector()
  const polygon_layer = new ol.layer.Vector({ source: polygon_source })
  map.addLayer(polygon_layer)
  const polygon = new ol.Feature(ol.geom.Polygon.fromExtent(rotated_extent))
  polygon_source.addFeature(polygon)