How to Determine the Area of a Polygon in OpenLayers 3

Polygons are a useful tool for representing the approximate area of a piece of land on a map, and knowing the size of the polygon you’ve drawn can be useful in many situations. This is possible with OpenLayers 3, a powerful JavaScript mapping tool that is free to download.

This article will walk you through the process of adding a polygon and then calculating the area of the polygon using a sphere.

Please keep in mind that in order to follow along with this article, you must have a functional OpenLayers map installed in a webpage. If you don’t have one, you can borrow one from a friend. OpenLayers 3: How to Create a Map Using the Program

Steps

1. Create a polygonal feature for your application. To use the Polygon function Object() { [native code] } function, you must first create an array of coordinate arrays, which you should store in a variable so that you can access it later. Simply copy and paste the following line of code into your script>/script> element to get started:

var coordinates = [[10, 20], [20, 30], [30, 20], [20, 10]];

var polygon_feature = new ol.Feature({

  geometry: new ol.geom.Polygon(

    [coordinates]

  )

});

2. Add the feature to a vector layer to make it more visible. If you want to add a polygon to the map, you must first add it to a source, which you then add to a vector layer, which you can then drag and drop onto the map:

var vector_layer = new ol.layer.Vector({

  source: new ol.source.Vector({

    features: [polygon_feature]

  })

})

map.addLayer(vector_layer);

3. 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);

4. Create a sphere to use as a work surface for the calculation. The sphere should be approximately the same size as the Earth (should have a radius of 6.3m meters). Speculatively, the WGS84 ellipsoid’s semi-major axis is the radius of the sphere, which is the same as the radius of the sphere.

var sphere = new ol.Sphere(6378137);

5. Using the geodesicArea() method, calculate the area of the sphere using the data from the sphere. Because the method provides a value in square metres, multiply the result by a million to get the equivalent in 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²

6. Double-check to see if the area answer makes any sense. Due to the fact that it appears to be approximately the same size as Algeria, which has a land area of 2,381,741 km2, we can be confident that it is correct (from Wikipedia).

Creative Commons License

Visit for: |  Auto  |  Games  |  Health  |  How To  |  Latest Review  |  News  |  Sports   |  Tech  |  Outsourcing  |