Polygons are a great way to represent the approximate area of land on a map, and it’s often helpful to know the area of the polygon you have defined. This is possible in OpenLayers 3; a powerful JavaScript mapping tool.

This article will guide you in adding a polygon, then getting the area calculated using a sphere.

Please note that you need to have a working OpenLayers map installed in a webpage to follow this article. If you don’t have one, How to Make a Map Using OpenLayers 3.

Steps

1Create a polygon feature. The Polygon constructor function needs an array of coordinate arrays; define this array in a variable first so that you can use it later. Simply copy the following of code into your <script></script> element:.var coordinates = , , , ];var polygon_feature = new ol.Feature();

2Add the feature to a vector layer. To add the polygon to the map, you need to add it to a source, which you add to a vector layer, which you can then add to the map:var vector_layer = new ol.layer.Vector()})map.addLayer(vector_layer);

3Transform the feature’s geometry to use coordinates.var current_projection = new ol.proj.Projection();var new_projection = tile_layer.getSource().getProjection();polygon_feature.getGeometry().transform(current_projection, new_projection);

4Create a sphere to perform the calculation. The sphere should be the size of the Earth (should have a radius of 6.3m meters). Technically, the sphere has a radius is equal to the semi-major axis of the WGS84 ellipsoid.var sphere = new ol.Sphere(6378137);

5Use the sphere to calculate the area using the geodesicArea() method. Because the method provides a value in square metres, divide by a million to get square kilometres. var area_m = sphere.geodesicArea(coordinates);var area_km = area_m / 1000 / 1000;console.log(‘area: ‘, area_km, ‘km²’);// CONSOLE: area: 2317133.7166773956 km²

6Check that the area answer makes sense. We know that it’s correct because it appears to be approximately the same size as Algeria, which has an area of 2,381,741 km² (from Wikipedia).