How to Determine the Area of a Polygon in OpenLayers 3. 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.
ADVERTISEMENT
ADVERTISEMENT
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.
- Create 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 line of code into your
<script></script> element:
.var coordinates = [[10, 20], [20, 30], [30, 20], [20, 10]]; var polygon_feature = new ol.Feature({ geometry: new ol.geom.Polygon( [coordinates] ) });
- Add 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({ source: new ol.source.Vector({ features: [polygon_feature] }) }) map.addLayer(vector_layer);
- Transform the feature’s geometry to use coordinates.
var current_projection = new ol.proj.Projection({code: "EPSG:4326"}); var new_projection = tile_layer.getSource().getProjection(); polygon_feature.getGeometry().transform(current_projection, new_projection);
- Create 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);
- Use 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²
- Check 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).
- Determine the Area of a Polygon
ADVERTISEMENT
Was this article helpful?
YesNo