1

I cannot find an API to rotate a feature/geometry in OpenLayers3. How do I rotate a polygon in OpenaLayers3?

1
  • 3
    Unfortunately this is not supported at this point.
    – erilem
    Commented Jan 28, 2015 at 11:36

1 Answer 1

1

You can now rotate a polygon with OpenLayers. Rotation unit is in radians and you also need to set a point to made rotation as seen in the API (link to parent class ol/geom/geometry that ol​/geom/Polygon inherits from)

You can see a demo I made. Below, in my sample (only JS mentioned), I use the center of the bounding box of the polygon.

To really center from centroid of the polygon, you would need to introduce JSTS, Turf (cf https://github.com/openlayers/openlayers/issues/3731#issuecomment-106718083) or use getInteriorPoint (for polygon) or getInteriorPoints (for multipolygon)

import "ol/ol.css";
import GeoJSON from "ol/format/GeoJSON";
import Map from "ol/Map";
import VectorLayer from "ol/layer/Vector";
import VectorSource from "ol/source/Vector";
import View from "ol/View";
import { Fill, Stroke, Style } from "ol/style";
import { getCenter } from "ol/extent";
import { fromLonLat } from "ol/proj";

var style = new Style({
  fill: new Fill({
    color: "rgba(255, 255, 255, 0.6)"
  }),
  stroke: new Stroke({
    color: "#319FD3",
    width: 1
  })
});

var vectorSource = new VectorSource();

var vectorLayer = new VectorLayer({
  source: vectorSource,
  style: style
});

new Map({
  layers: [vectorLayer],
  target: "map",
  view: new View({
    center: fromLonLat([1, 45]),
    zoom: 2
  })
});

fetch("data/geojson/countries.geojson")
  .then((r) => r.json())
  .then((json) => {
    var features = new GeoJSON({ featureProjection: "EPSG:3857" }).readFeatures(
      json
    );
    vectorSource.addFeatures(features);
    var feature1 = vectorLayer
      .getSource()
      .getFeatures()
      .find((el) => el.get("name") === "France");
    var geom1 = feature1.getGeometry();
    var xy = getCenter(geom1.getExtent());
    geom1.rotate(-90 * (Math.PI / 180), xy);
});

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Not the answer you're looking for? Browse other questions tagged or ask your own question.