Tuesday 11 June 2019

Get Center of Geometry 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.



Answer



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!


No comments:

Post a Comment

arcpy - Changing output name when exporting data driven pages to JPG?

Is there a way to save the output JPG, changing the output file name to the page name, instead of page number? I mean changing the script fo...