1

I am using OpenLayers latest version. Using a APIRest, I fetch a PostGIS endpoint and get a response in GeoJSON format.

Then this is used to create a source and a layer :

....
const response = await myfetch.json()
const opeGeoJsonFormat = new GeoJSON({
 dataProjection: "EPSG:2154",
 featureProjection: "EPSG:3857",
})
...
const ope = opeGeoJsonFormat.readFeatures(response)

const opeSource = new VectorSource({
  features: ope,
})

opeCouche = new VectorLayer({
  source: opeSource,
  style: styleOpeCouche,
  title: "opérations",
})

From the response, I would like to create clusters. Here is what I have done :

 const featuresPoint = []
 ope.forEach(operation => {
  const coordOpeTableau = operation.getGeometry().flatCoordinates
  const polygon = new Polygon(
    coordOpeTableau,
    "XY",
    coordOpeTableau.length - 1
  )
  const pointInterieur = polygon.getInteriorPoint()
  featuresPoint.push(new Feature(pointInterieur))
})   

Then I have created a cluster source and a layer. So far so good.

I wonder if there is a way of creating the clusters points without using new Polygon class, since the geometries returned by the response are multipolygon? I can't do it actually, but I am not an expert developer.

2
  • If I understand correctly, you want to get centroid of multipolygon geometry?
    – TomazicM
    Commented Feb 20 at 12:10
  • yes, and I wonder if it is possile without tjhe step of new Polygon but directly from ope.
    – Leehan
    Commented Feb 20 at 15:14

1 Answer 1

0

The simplest way to get centroid directly from GeoJSON feature seems to be to use turf.js library and it's turf.centroid method.

Relevant part of the code would then be (assuming data is in EPSG:4326 and features are in EPSG:3857 CRS):

const formatGeoJSON = new ol.format.GeoJSON({
  dataProjection:'EPSG:4326',
  featureProjection: 'EPSG:3857'
});
var featuresPoint = [];

turf.featureEach(response, function(feature) {
  const centroid = turf.centroid(feature);
  const pointFeature = formatGeoJSON.readFeature(centroid);
  featuresPoint.push(pointFeature);
});
2
  • Thanks. I will try asap and will be back.
    – Leehan
    Commented Feb 21 at 8:44
  • Thanks, it works. I just notice that response is json although the doc says that the first argument has to be a GeoJSON.
    – Leehan
    Commented Feb 22 at 9:26

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.