Learn how to calculate the length and area of geometries.
You can calculate the length of a line and determine the area of a polygon using the geometryEngine. The measurement depends on the coordinate system (or spatial reference) defined for the geometry. If the geometry's spatial reference is Web Mercator (3857) or WGS84 (4326), you would use geodesic calculations to take into account the curvature of the Earth. If the spatial reference is something different from Web Mercator (3857) or WGS84 (4326), you would use planar measurements based on Euclidean distances.
In this tutorial, you will use the Sketch component to draw graphics on the view and the geometryEngine to calculate both geodesic and planar lengths and areas to see the difference between the two measurements.
Prerequisites
Steps
Create a new pen
- To get started, either complete the Display a map tutorial or .
Get an access token
You need an access token with the correct privileges to access the location services used in this tutorial.
- Go to the Create an API key tutorial and create an API key with the following privilege(s):
- Privileges
- Location services > Basemaps
- Privileges
- In CodePen, set
esri
to your access token.Config.api Key Use dark colors for code blocks var esriConfig = { apiKey: "YOUR_ACCESS_TOKEN" };
To learn about other ways to get an access token, go to Types of authentication.
Recenter the map and add a scalebar
The ScaleBar component will display a scale bar on the map. You can choose either metric or imperial values. For example, if you set the unit
attribute to metric
, it will show kilometers or meters, depending on the scale.
-
Change the
center
andzoom
attributes on thearcgis-map
.Use dark colors for code blocks <arcgis-map basemap="arcgis/topographic" center="-10, 30" zoom="3"> <arcgis-zoom position="top-left"></arcgis-zoom> </arcgis-map>
-
Add an
arcgis-scalebar
component to the bottom left of the map and set itsunit
attribute to be"metric"
.Use dark colors for code blocks <arcgis-map basemap="arcgis/topographic" center="-10, 30" zoom="3"> <arcgis-zoom position="top-left"></arcgis-zoom> <!-- Scale bar component --> <arcgis-scale-bar position="bottom-left" unit="metric"></arcgis-scale-bar> </arcgis-map>
-
Run the app to verify the change in the
center
andzoom
level. Thescalebar
should appear at the bottom left of the map.
Add the Sketch component
The Sketch component provides UI that allows you to create and update graphics.
-
Add an
arcgis-sketch
component to the top-right corner of the map. Any geometry drawn using the component will be added to a GraphicsLayer that the component will create for us as itslayer
property. To simplify the user interface, limit the tools available on the component by setting the appropriate attributes.Use dark colors for code blocks <arcgis-map basemap="arcgis/topographic" center="-10, 30" zoom="3"> <arcgis-zoom position="top-left"></arcgis-zoom> <!-- Scale bar component --> <arcgis-scale-bar position="bottom-left" unit="metric"></arcgis-scale-bar> <!-- Sketch component --> <arcgis-sketch creation-mode="update" hide-selection-tools-lasso-selection hide-selection-tools-rectangle-selection hideSnappingControls hide-undo-redo-menu hide-settings-menu position="top-right" ></arcgis-sketch> </arcgis-map>
-
Run the app to verify that the component appears in the view and that you can draw graphics.
Add HTML to display measurements
-
Add an
arcgis-placement
component and inside of the element tags place adiv
to display the results of a calculation in the bottom-right corner of the map.Use dark colors for code blocks <!-- Sketch component --> <arcgis-sketch creation-mode="update" hide-selection-tools-lasso-selection hide-selection-tools-rectangle-selection hideSnappingControls hide-undo-redo-menu hide-settings-menu position="top-right" ></arcgis-sketch> <!-- Placement component --> <arcgis-placement position="bottom-right"> <div id="measurementsDiv"></div> </arcgis-placement>
-
Add some CSS styling to set the background-color, border-radius and padding.
Use dark colors for code blocks <style> html, body { margin: 0; } arcgis-map { display: block; height: 100vh; } #measurementsDiv { background-color: white; border-radius: 6px; padding: 6px; } </style>
Add modules
-
Use an AMD
require
statement to add the necessary modules in a new<script
at the bottom of the> <body
.> The ArcGIS Maps SDK for JavaScript is available as AMD modules and ES modules, but this tutorial is based on AMD. The AMD
require
function uses references to determine which modules will be loaded – for example, you can specify"esri/layers/
for loading the FeatureLayer module. After the modules are loaded, they are passed as parameters (e.g.Feature Layer" Feature
) to the callback function where they can be used in your application. It is important to keep the module references and callback parameters in the same order. To learn more about the API's different modules visit the Overview Guide page.Layer Use dark colors for code blocks <script> require([ "esri/Graphic", "esri/geometry/geometryEngine", "esri/geometry/Polygon", "esri/geometry/Polyline", "esri/symbols/SimpleFillSymbol" ], (Graphic, geometryEngine, Polygon, Polyline, SimpleFillSymbol) => { }); </script>
Get references to the sketch and the measurements elements
-
Use the
document.query
method to get a reference to theSelector arcgis-sketch
component and the#measurements
.Div Use dark colors for code blocks <script> require([ "esri/Graphic", "esri/geometry/geometryEngine", "esri/geometry/Polygon", "esri/geometry/Polyline", "esri/symbols/SimpleFillSymbol" ], (Graphic, geometryEngine, Polygon, Polyline, SimpleFillSymbol) => { // Get references to the arcgis-sketch component and measurementsDiv elements const arcgisSketch = document.querySelector("arcgis-sketch"); const measurementsDiv = document.querySelector("#measurementsDiv"); }); </script>
Set properties on the sketch component
-
Set the
available
property on the sketch component to further refine the available tools.Create Tools Use dark colors for code blocks <script> require([ "esri/Graphic", "esri/geometry/geometryEngine", "esri/geometry/Polygon", "esri/geometry/Polyline", "esri/symbols/SimpleFillSymbol" ], (Graphic, geometryEngine, Polygon, Polyline, SimpleFillSymbol) => { // Get references to the arcgis-sketch component and measurementsDiv elements const arcgisSketch = document.querySelector("arcgis-sketch"); const measurementsDiv = document.querySelector("#measurementsDiv"); // Set the available create tools for the arcgis-sketch component arcgisSketch.availableCreateTools = ["polyline", "polygon", "rectangle"]; }); </script>
Create function to calculate length and area
The geometry
allows you to calculate a geometry's planar length/area or geodesic length/area. Because the geometries in this application are projected in Web Mercator, it is best practice to use geodesic measurements. In this tutorial, we calculate both when a graphic is drawn to visualize the difference between geodesic and planar calculations.
-
Create a
get
function that takes aArea polygon
as its parameter. Call thegeodesic
method and theArea planar
methods to calculate the area of the polygon inArea square-kilometers
. Append the calculation results to theinner
ofHTML measurements
.Div Use dark colors for code blocks // A function to get the area of a polygon function getArea(polygon) { const geodesicArea = geometryEngine.geodesicArea(polygon, "square-kilometers"); const planarArea = geometryEngine.planarArea(polygon, "square-kilometers"); measurementsDiv.innerHTML = "<b>Geodesic area</b>: " + geodesicArea.toFixed(2) + " km\xB2" + " | <b>Planar area</b>: " + planarArea.toFixed(2) + " km\xB2"; }
-
Create a
get
function that takes aLength line
parameter. Call thegeodesic
andLength planar
methods to calculate the length of theLength line
in kilometers. Append the results of the geodesic length calculation to theinner
of theHTML measurements
.Div Use dark colors for code blocks // A function to get the area of a polygon function getArea(polygon) { const geodesicArea = geometryEngine.geodesicArea(polygon, "square-kilometers"); const planarArea = geometryEngine.planarArea(polygon, "square-kilometers"); measurementsDiv.innerHTML = "<b>Geodesic area</b>: " + geodesicArea.toFixed(2) + " km\xB2" + " | <b>Planar area</b>: " + planarArea.toFixed(2) + " km\xB2"; } // A function to get the length of a polyline function getLength(line) { const geodesicLength = geometryEngine.geodesicLength(line, "kilometers"); const planarLength = geometryEngine.planarLength(line, "kilometers"); measurementsDiv.innerHTML = "<b>Geodesic length</b>: " + geodesicLength.toFixed(2) + " km" + " | <b>Planar length</b>: " + planarLength.toFixed(2) + " km"; }
-
Create a
get
function that will either call theMeasurements get
function or theArea get
function depending on whether the geometry is aLength polygon
or apolyline
.Use dark colors for code blocks // A function to get the length of a polyline function getLength(line) { const geodesicLength = geometryEngine.geodesicLength(line, "kilometers"); const planarLength = geometryEngine.planarLength(line, "kilometers"); measurementsDiv.innerHTML = "<b>Geodesic length</b>: " + geodesicLength.toFixed(2) + " km" + " | <b>Planar length</b>: " + planarLength.toFixed(2) + " km"; } // A function to get the measurements of a geometry function getMeasurements(geometry) { switch (geometry.type) { case "polygon": getArea(geometry); break; case "polyline": getLength(geometry); break; default: console.log("No value found"); } }
Create a graphic to measure
To show the user how to interact with the application, create a polygon and display its area when the app starts.
-
Create a new Polygon. Set the the
wkid
in thespatial
property toReference 3857
(Web Mercator). To style the graphic, create a SimpleFillSymbol.Use dark colors for code blocks // Create a polygon geometry const polygon = new Polygon({ spatialReference: { wkid: 3857 }, rings: [ [ [-4508069.082189632, 3599936.936171892], [-4508069.082189632, 5478453.343307884], [-2629552.6750536393, 5478453.343307884], [-2629552.6750536393, 3599936.936171892], [-4508069.082189632, 3599936.936171892] ] ] }); // Create a simple fill symbol const simpleFillSymbol = new SimpleFillSymbol({ outline: { color: [200, 0, 0], width: 2 } });
-
Create an instance of the Graphic class. Set the
geometry
andsymbol
property values to thepolygon
andsimple
.Fill Symbol Use dark colors for code blocks // Create a polygon geometry const polygon = new Polygon({ spatialReference: { wkid: 3857 }, rings: [ [ [-4508069.082189632, 3599936.936171892], [-4508069.082189632, 5478453.343307884], [-2629552.6750536393, 5478453.343307884], [-2629552.6750536393, 3599936.936171892], [-4508069.082189632, 3599936.936171892] ] ] }); // Create a simple fill symbol const simpleFillSymbol = new SimpleFillSymbol({ outline: { color: [200, 0, 0], width: 2 } }); // Create a polygon graphic const polygonGraphic = new Graphic({ geometry: polygon, symbol: simpleFillSymbol });
Add event listeners
Add event listeners to the Sketch component to listen for when the user adds a polygon graphic to the map. Create another event listener to calculate the length and area of the graphic when it's updated.
-
Add an event listener to the sketch component to wait for it to be ready, then add the polygon graphic to the component's graphics layer. Call the component's
update
method on thepolygon
and call theGraphic get
function based on theArea geometry
of thepolygon
.Graphic Use dark colors for code blocks // Add the polygon graphic to the arcgis-sketch layer when the arcgis-sketch is ready // and update the the measurementsDiv with the area of the polygon arcgisSketch?.addEventListener("arcgisReady", () => { arcgisSketch?.layer.add(polygonGraphic); arcgisSketch.update(polygonGraphic); getArea(polygonGraphic.geometry); });
-
Create an event listener on the sketch component that listens to the
arcgis
event. This event is emitted when you create, resize, or move a graphic. Save theUpdate geometry
of the first graphic from theevent.detail.graphics
collection as a constant.Use dark colors for code blocks // Add the polygon graphic to the arcgis-sketch layer when the arcgis-sketch is ready // and update the the measurementsDiv with the area of the polygon arcgisSketch?.addEventListener("arcgisReady", () => { arcgisSketch?.layer.add(polygonGraphic); arcgisSketch.update(polygonGraphic); getArea(polygonGraphic.geometry); }); // Listen for the arcgisUpdate event and update the measurementsDiv // based on the new geometry arcgisSketch?.addEventListener("arcgisUpdate", (event) => { const geometry = event.detail.graphics[0].geometry; });
-
Create conditional statements based on whether the
sketch
event'sstate
is:start
,complete
, or in a state of change. Except forcomplete
, each state calls theget
function with theMeasurements geometry
as its parameter. When the event iscomplete
, remove the graphic from the sketch component's layer and clear theinner
.HTML Use dark colors for code blocks // Listen for the arcgisUpdate event and update the measurementsDiv // based on the new geometry arcgisSketch?.addEventListener("arcgisUpdate", (event) => { const geometry = event.detail.graphics[0].geometry; if (event.detail.state === "start") { getMeasurements(geometry); } if (event.detail.state === "complete") { arcgisSketch.layer.remove(arcgisSketch.layer.graphics.getItemAt(0)); measurementsDiv.innerHTML = ""; } if ( event.detail.toolEventInfo && (event.detail.toolEventInfo.type === "scale-stop" || event.detail.toolEventInfo.type === "reshape-stop" || event.detail.toolEventInfo.type === "move-stop") ) { getMeasurements(geometry); } });
Run the app
In CodePen, run your code to display the map.
When you run the app, you will see a polygon with its calculated geodesic and planar area. You can use the sketch component to draw other geometries and display their measurements. If you move the geometry, the geodesic measurements will change but the planar measurements will not.
What's next?
Learn how to use additional API features and ArcGIS services in these tutorials: