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.
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.
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
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!
`var x = extent[0] + (extent[2] - extent[0]) / 2;
var y = extent[1] + (extent[3] - extent[1]) / 2;`
– Gerrit Fölster Feb 11 '15 at 07:49getCenterOfExtent
– Joel
Mar 25 '15 at 16:07
ol.extent.getCenter and its stable. For example, I did var aa = e.selected[0].getGeometry().getExtent(); var oo = ol.extent.getCenter(aa); and gave me the center of points, lines and polygons. Check it out here
– slevin
Oct 21 '15 at 17:22
You can also get the center with:
var center = e.feature.getGeometry().getCenter();
Uncaught TypeError: feature.getGeometry(...).getCenter is not a function.
– Dirk
May 20 '16 at 10:22
getCenter() method is only applicable to circle geometries ol.geom.Circle. Is it possible that you have a different type of geometry?
– Bwyss
May 22 '16 at 14:21
OpenLayers v 6.1.1
var center = e.feature.getGeometry().getExtent().getCenter()