TransWikia.com

Get Center of Geometry in OpenLayers 3

Geographic Information Systems Asked by Joseph Ravenwolfe on February 8, 2021

Given a Geometry object in OpenLayers 3. How would one go about getting its center?

Older versions of OpenLayers provided a getCentroid method. There was also a getBounds workaround. But these appear to be removed in OpenLayers 3.

5 Answers

Bit of a workaround but you can use the getExtent method on the geometry to set the extent on the map. I presume the center of the view will then be the center of the geometry;

Test = new ol.geom.Geometry();
map.getView().fitExtent(Test.getExtent, map.getSize());
var CenterOfGeom = map.getView().getCenter()

If you do not want to change the view (which I can imagine), you can think of a function to calculate the center of the extent. This will be easy in certain types of coordinate systems (EPSG:3857, which is meter based), but more difficult in others (EPSG:4326, based on lon/lat coords). A function which could calculate this center (in EPSG:3857) would be as following;

function getCenterOfExtent(Extent){
var X = Extent[0] + (Extent[2]-Extent[0])/2;
var Y = Extent[1] + (Extent[3]-Extent[1])/2;
return [X, Y];
}

Hope this helps!

Answered by Tim.Lucas on February 8, 2021

You can get its extent center using ol.extent.getCenter. In my case I have a vector layer and I want to get the center of a feature after I click it.

So

create a simple click interaction and add it to the map

 var select = new ol.interaction.Select();
 map.addInteraction(select);

For each click...

select.on('select', function(e) {

Get the first feature that is selected, from the "selected" array. Then get its geometry, and then its extent.

Use that extent to find its center, using ol.extent.getCenter

    var aa = e.selected[0].getGeometry().getExtent();
    var oo = ol.extent.getCenter(aa);
    console.log("The center is :  "+oo); // voila!!!!

 });

The same code worked for lines, points, and polygons.

PS. The ol.extent.getCenter is stable, used in OL version 3.9.0 and version 3.10.1 and can you can find it here

Answered by slevin on February 8, 2021

You can also get the center with:

var center = e.feature.getGeometry().getCenter();

Answered by Bwyss on February 8, 2021

OpenLayers v 6.1.1

var center = e.feature.getGeometry().getExtent().getCenter()

Answered by lord5et on February 8, 2021

If your geometry contains polygon or multipolygon, try to use ol​/geom​/Polygon.getInteriorPoint or ol​/geom​/MultiPolygon.getInteriorPoints that good to get inner point(s).

Example for Polygon

let geom = feature.getGeometry();
let polygon = geom.getPolygon(0);
let XYM = polygon.getInteriorPoint();
let coordinate = XYM.getCoordinates();

Answered by Riddle on February 8, 2021

Add your own answers!

Ask a Question

Get help from others!

© 2024 TransWikia.com. All rights reserved. Sites we Love: PCI Database, UKBizDB, Menu Kuliner, Sharing RPP