Hide Table of Contents
View Measure distances sample in sandbox
Measure distances

Description

This example shows how you can use an ArcGIS Server geometry service to measure line lengths in your Web application. When you click and drag the mouse, the Draw toolbar captures the geometry of the line you drew. It sends the line to the geometry service, which calculates the length of the line using the GeometryService.lengths() method.

Code

<!DOCTYPE html>
<html>
  <head>
    <meta http-equiv="Content-Type" content="text/html; charset=utf-8">
  
  <meta name="viewport" content="initial-scale=1, maximum-scale=1,user-scalable=no">
   <title>Measure Distances</title>
  <link rel="stylesheet" href="https://js.arcgis.com/3.46/dijit/themes/claro/claro.css">
  <link rel="stylesheet" href="https://js.arcgis.com/3.46/esri/css/esri.css">

  <script src="https://js.arcgis.com/3.46/"></script>
  <script>
    dojo.require("esri.map");
    dojo.require("esri.tasks.geometry");
    dojo.require("esri.toolbars.draw");
    dojo.require("dojo.number");

    var map, geometryService;

    function init() {
      map = new esri.Map("map", {
        basemap: "streets-vector",
        center: [-77.500, 42.500],
        zoom: 7
      });
      dojo.connect(map, "onLoad", initFunctionality);
      geometryService = new esri.tasks.GeometryService("https://utility.arcgisonline.com/ArcGIS/rest/services/Geometry/GeometryServer");
      dojo.connect(geometryService, "onLengthsComplete", outputDistance);
    }

    function initFunctionality(map) {
      var tb = new esri.toolbars.Draw(map);
      var lengthParams = new esri.tasks.LengthsParameters();
      //on draw end add graphic, project it, and get new length
      dojo.connect(tb, "onDrawEnd", function(geometry) {
        map.graphics.clear();

        lengthParams.polylines = [geometry];
        lengthParams.lengthUnit = esri.tasks.GeometryService.UNIT_METER;
        lengthParams.geodesic = true;

        geometryService.lengths(lengthParams);
        var graphic = map.graphics.add(new esri.Graphic(geometry, new esri.symbol.SimpleLineSymbol()));
      });
      tb.activate(esri.toolbars.Draw.FREEHAND_POLYLINE);
    }

    function outputDistance(result) {
      dojo.byId("distance").innerHTML = dojo.number.format(result.lengths[0] / 1000) + " kilometers";
    }

    dojo.ready(init);
  </script>

  </head>
  <body>
    Click and hold down on the map to draw a line that will be added to the map.  The application will then use the geometry service to project and compute the length of the line.
    <div id="map" class="claro" style="width:1024px; height:512px; border:1px solid #000;"></div>
    Distance: <span id="distance"></span>
  </body>
</html>
 
          
Show Modal