Get Center of Geometry in OpenLayers 3

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!


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