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 geometry operators. 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 geometry operators 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
esrito 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
centerandzoomattributes on thearcgis-map.Use dark colors for code blocks <arcgis-map basemap="arcgis/topographic" center="-10, 30" zoom="3"> <arcgis-zoom slot="top-left"></arcgis-zoom> </arcgis-map> -
Add an
arcgis-scalebarcomponent to the bottom left of the map and set itsunitattribute to be"metric".Use dark colors for code blocks <arcgis-map basemap="arcgis/topographic" center="-10, 30" zoom="3"> <arcgis-zoom slot="top-left"></arcgis-zoom> <!-- Scale bar component --> <arcgis-scale-bar slot="bottom-left" unit="metric"></arcgis-scale-bar> </arcgis-map> -
Run the app to verify the change in the
centerandzoomlevel. Thescalebarshould 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-sketchcomponent 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 itslayerproperty. 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 slot="top-left"></arcgis-zoom> <!-- Scale bar component --> <arcgis-scale-bar slot="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 slot="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 a
divto display the results of a calculation in the bottom-right slot 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 slot="top-right"></arcgis-sketch> <div id="measurementsDiv" slot="bottom-right"></div> -
Add some CSS styling to set the background-color, border-radius and padding.
Use dark colors for code blocks <style> html, body { height: 100%; margin: 0; } #measurementsDiv { background-color: white; border-radius: 6px; padding: 6px; } </style>
Add modules
-
Use
$arcgis.importto add the necessary modules in a new<scriptat the bottom of the> <body.> The ArcGIS Maps SDK for JavaScript is available via CDN and npm, but this tutorial is based on CDN. The
$arcgis.importglobal function accepts a module path or array of module paths, and returns a promise that resolves with the requested modules. This function can only be used when working with the CDN; otherwise, use the standard import syntax. To learn more about the SDK's different modules, visit the References page.Use dark colors for code blocks <script type="module"> const [ Graphic, areaOperator, geodeticAreaOperator, geodeticLengthOperator, lengthOperator, Polygon, Polyline, SimpleFillSymbol, ] = await $arcgis.import([ "@arcgis/core/Graphic.js", "@arcgis/core/geometry/operators/areaOperator.js", "@arcgis/core/geometry/operators/geodeticAreaOperator.js", "@arcgis/core/geometry/operators/geodeticLengthOperator.js", "@arcgis/core/geometry/operators/lengthOperator.js", "@arcgis/core/geometry/Polygon.js", "@arcgis/core/geometry/Polyline.js", "@arcgis/core/symbols/SimpleFillSymbol.js", ]); </script>
Get references to the sketch and the measurements elements
-
Use the
document.querymethod to get a reference to theSelector arcgis-sketchcomponent and the#measurements.Div Use dark colors for code blocks <script type="module"> const [ Graphic, areaOperator, geodeticAreaOperator, geodeticLengthOperator, lengthOperator, Polygon, Polyline, SimpleFillSymbol, ] = await $arcgis.import([ "@arcgis/core/Graphic.js", "@arcgis/core/geometry/operators/areaOperator.js", "@arcgis/core/geometry/operators/geodeticAreaOperator.js", "@arcgis/core/geometry/operators/geodeticLengthOperator.js", "@arcgis/core/geometry/operators/lengthOperator.js", "@arcgis/core/geometry/Polygon.js", "@arcgis/core/geometry/Polyline.js", "@arcgis/core/symbols/SimpleFillSymbol.js", ]); // 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
availableproperty on the sketch component to further refine the available tools.Create Tools Use dark colors for code blocks <script type="module"> const [ Graphic, areaOperator, geodeticAreaOperator, geodeticLengthOperator, lengthOperator, Polygon, Polyline, SimpleFillSymbol, ] = await $arcgis.import([ "@arcgis/core/Graphic.js", "@arcgis/core/geometry/operators/areaOperator.js", "@arcgis/core/geometry/operators/geodeticAreaOperator.js", "@arcgis/core/geometry/operators/geodeticLengthOperator.js", "@arcgis/core/geometry/operators/lengthOperator.js", "@arcgis/core/geometry/Polygon.js", "@arcgis/core/geometry/Polyline.js", "@arcgis/core/symbols/SimpleFillSymbol.js", ]); // 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 operators allow 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
getfunction that takes aArea polygonas its parameter. Use thegeodeticand theArea Operator areageometry operators to calculate the area of the polygon inOperator square-kilometers. Append the calculation results to theinnerofHTML measurements.Div Use dark colors for code blocks // A function to get the area of a polygon async function getArea(polygon) { if (!geodeticAreaOperator.isLoaded()) { await geodeticAreaOperator.load(); } const geodesicArea = geodeticAreaOperator.execute(polygon, { units: "square-kilometers" }); const planarArea = areaOperator.execute(polygon, { units: "square-kilometers" }); measurementsDiv.innerHTML = "<b>Geodesic area</b>: " + geodesicArea.toFixed(2) + " km\xB2" + " | <b>Planar area</b>: " + planarArea.toFixed(2) + " km\xB2"; } -
Create a
getfunction that takes aLength lineparameter. Use thegeodeticandLength Operator lengthgeometry operators to calculate the length of theOperator linein kilometers. Append the results of the geodesic length calculation to theinnerof theHTML measurements.Div Use dark colors for code blocks // A function to get the area of a polygon async function getArea(polygon) { if (!geodeticAreaOperator.isLoaded()) { await geodeticAreaOperator.load(); } const geodesicArea = geodeticAreaOperator.execute(polygon, { units: "square-kilometers" }); const planarArea = areaOperator.execute(polygon, { units: "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 async function getLength(line) { if (!geodeticLengthOperator.isLoaded()) { await geodeticLengthOperator.load(); } const geodesicLength = geodeticLengthOperator.execute(line, { units: "kilometers" }); const planarLength = lengthOperator.execute(line, { units: "kilometers" }); measurementsDiv.innerHTML = "<b>Geodesic length</b>: " + geodesicLength.toFixed(2) + " km" + " | <b>Planar length</b>: " + planarLength.toFixed(2) + " km"; } -
Create a
getfunction that will either call theMeasurements getfunction or theArea getfunction depending on whether the geometry is aLength polygonor apolyline.Use dark colors for code blocks // A function to get the length of a polyline async function getLength(line) { if (!geodeticLengthOperator.isLoaded()) { await geodeticLengthOperator.load(); } const geodesicLength = geodeticLengthOperator.execute(line, { units: "kilometers" }); const planarLength = lengthOperator.execute(line, { units: "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
wkidin thespatialproperty 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
geometryandsymbolproperty values to thepolygonandsimple.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
triggermethod on theUpdate polygonand call theGraphic getfunction based on theArea geometryof 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.triggerUpdate(polygonGraphic); getArea(polygonGraphic.geometry); }); -
Create an event listener on the sketch component that listens to the
arcgisevent. This event is emitted when you create, resize, or move a graphic. Save theUpdate geometryof the first graphic from theevent.detail.graphicscollection 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.triggerUpdate(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
sketchevent'sstateis:start,complete, or in a state of change. Except forcomplete, each state calls thegetfunction with theMeasurements geometryas 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 SDK features and ArcGIS services in these tutorials: