Distance measurement analysis

View on GitHubSample viewer app

Measure distances between two points in 3D.

Image of distance measurement analysis

Use case

The distance measurement analysis allows you to add to your app the same interactive measuring experience found in ArcGIS Pro, City Engine, and the ArcGIS API for JavaScript. You can set the unit system of measurement (metric or imperial). The units automatically switch to one appropriate for the current scale.

How to use the sample

Choose a unit system for the measurement. Click any location in the scene to start measuring. Move the mouse to an end location, and click to complete the measurement. Click a new location to clear and start a new measurement.

How it works

  1. Create an AnalysisOverlay object and add it to the analysis overlay collection of the SceneView object.
  2. Specify the start location and end location to create a LocationDistanceMeasurement object. Initially, the start and end locations can be the same point.
  3. Add the location distance measurement analysis to the analysis overlay.
  4. The measurementChanged callback will trigger if the distances change. You can get the new values for the directDistance, horizontalDistance, and verticalDistance from the MeasurementChangedEvent object returned by the callback.

Relevant API

  • AnalysisOverlay
  • LocationDistanceMeasurement

Additional information

The LocationDistanceMeasurement analysis only performs planar distance calculations. This may not be appropriate for large distances where the Earth's curvature must be considered.

Tags

3D, analysis, distance, measure

Sample Code

DistanceMeasurementAnalysisController.javaDistanceMeasurementAnalysisController.javaDistanceMeasurementAnalysisSample.java
Use dark colors for code blocksCopy
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
/*
 * Copyright 2018 Esri.
 *
 * Licensed under the Apache License, Version 2.0 (the "License"); you may not
 * use this file except in compliance with the License. You may obtain a copy of
 * the License at
 *
 * http://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS, WITHOUT
 * WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the
 * License for the specific language governing permissions and limitations under
 * the License.
 */

package com.esri.samples.distance_measurement_analysis;

import java.text.DecimalFormat;
import java.util.concurrent.ExecutionException;

import javafx.event.EventHandler;
import javafx.fxml.FXML;
import javafx.geometry.Point2D;
import javafx.scene.control.Alert;
import javafx.scene.control.ComboBox;
import javafx.scene.control.Label;
import javafx.scene.input.MouseButton;
import javafx.scene.input.MouseEvent;

import com.esri.arcgisruntime.ArcGISRuntimeEnvironment;
import com.esri.arcgisruntime.UnitSystem;
import com.esri.arcgisruntime.concurrent.ListenableFuture;
import com.esri.arcgisruntime.geoanalysis.LocationDistanceMeasurement;
import com.esri.arcgisruntime.geometry.Distance;
import com.esri.arcgisruntime.geometry.Point;
import com.esri.arcgisruntime.geometry.SpatialReferences;
import com.esri.arcgisruntime.layers.ArcGISSceneLayer;
import com.esri.arcgisruntime.loadable.LoadStatus;
import com.esri.arcgisruntime.mapping.ArcGISScene;
import com.esri.arcgisruntime.mapping.ArcGISTiledElevationSource;
import com.esri.arcgisruntime.mapping.BasemapStyle;
import com.esri.arcgisruntime.mapping.Surface;
import com.esri.arcgisruntime.mapping.view.AnalysisOverlay;
import com.esri.arcgisruntime.mapping.view.Camera;
import com.esri.arcgisruntime.mapping.view.SceneView;

public class DistanceMeasurementAnalysisController {

  @FXML private SceneView sceneView;
  @FXML private Label directDistanceLabel;
  @FXML private Label verticalDistanceLabel;
  @FXML private Label horizontalDistanceLabel;
  @FXML private ComboBox<UnitSystem> unitSystemComboBox;

  private LocationDistanceMeasurement distanceMeasurement;

  public void initialize() {

    // authentication with an API key or named user is required to access basemaps and other location services
    String yourAPIKey = System.getProperty("apiKey");
    ArcGISRuntimeEnvironment.setApiKey(yourAPIKey);

    // create a scene with a basemap style and set it to the scene view
    ArcGISScene scene = new ArcGISScene(BasemapStyle.ARCGIS_TOPOGRAPHIC);
    sceneView.setArcGISScene(scene);

    // add base surface for elevation data
    Surface surface = new Surface();
    surface.getElevationSources().add(new ArcGISTiledElevationSource(
      "https://elevation3d.arcgis.com/arcgis/rest/services/WorldElevation3D/Terrain3D/ImageServer"));
    scene.setBaseSurface(surface);

    final String buildings = "http://tiles.arcgis.com/tiles/P3ePLMYs2RVChkJx/arcgis/rest/services/Buildings_Brest/SceneServer/layers/0";
    ArcGISSceneLayer sceneLayer = new ArcGISSceneLayer(buildings);
    sceneLayer.setAltitudeOffset(1); // offset for visual purposes
    scene.getOperationalLayers().add(sceneLayer);

    // create an analysis overlay and add it to the scene view
    AnalysisOverlay analysisOverlay = new AnalysisOverlay();
    sceneView.getAnalysisOverlays().add(analysisOverlay);

    // initialize a distance measurement and add it to the analysis overlay
    Point start = new Point(-4.494677, 48.384472, 24.772694, SpatialReferences.getWgs84());
    Point end = new Point(-4.495646, 48.384377, 58.501115, SpatialReferences.getWgs84());
    distanceMeasurement = new LocationDistanceMeasurement(start, end);
    analysisOverlay.getAnalyses().add(distanceMeasurement);

    // zoom to the initial measurement
    scene.addDoneLoadingListener(() -> {
      if (scene.getLoadStatus() == LoadStatus.LOADED) {
        sceneView.setViewpointCamera(new Camera(start, 200.0, 0.0, 45.0, 0.0));
      } else {
        new Alert(Alert.AlertType.ERROR, "Scene failed to load").show();
      }
    });

    // show the distances in the UI when the measurement changes
    DecimalFormat decimalFormat = new DecimalFormat("#.##");
    distanceMeasurement.addMeasurementChangedListener(e -> {
      Distance directDistance = e.getDirectDistance();
      Distance verticalDistance = e.getVerticalDistance();
      Distance horizontalDistance = e.getHorizontalDistance();
      directDistanceLabel.setText(decimalFormat.format(directDistance.getValue()) + " " + directDistance.getUnit()
          .getAbbreviation());
      verticalDistanceLabel.setText(decimalFormat.format(verticalDistance.getValue()) + " " + verticalDistance
          .getUnit().getAbbreviation());
      horizontalDistanceLabel.setText(decimalFormat.format(horizontalDistance.getValue()) + " " + horizontalDistance
          .getUnit().getAbbreviation());
    });

    // add the unit system options to the UI initialized with the measurement's default value (METRIC)
    unitSystemComboBox.getItems().addAll(UnitSystem.values());
    unitSystemComboBox.setValue(distanceMeasurement.getUnitSystem());

    // remove the default mouse move handler
    sceneView.setOnMouseMoved(null);

    // create a handler to update the measurement's end location when the mouse moves
    EventHandler<MouseEvent> mouseMoveEventHandler = event -> {
      Point2D point2D = new Point2D(event.getX(), event.getY());
      // get the scene location from the screen position
      ListenableFuture<Point> pointFuture = sceneView.screenToLocationAsync(point2D);
      pointFuture.addDoneListener(() -> {
        try {
          // update the end location
          Point point = pointFuture.get();
          distanceMeasurement.setEndLocation(point);
        } catch (InterruptedException | ExecutionException e) {
          e.printStackTrace();
        }
      });
    };

    // mouse click to start/stop moving a measurement
    sceneView.setOnMouseClicked(event -> {
      if (event.isStillSincePress() && event.getButton() == MouseButton.PRIMARY) {
        // get the clicked location
        Point2D point2D = new Point2D(event.getX(), event.getY());
        ListenableFuture<Point> pointFuture = sceneView.screenToLocationAsync(point2D);
        pointFuture.addDoneListener(() -> {
          try {
            Point point = pointFuture.get();
            if (sceneView.getOnMouseMoved() == null) {
              // reset the measurement at the clicked location and start listening for mouse movement
              sceneView.setOnMouseMoved(mouseMoveEventHandler);
              distanceMeasurement.setStartLocation(point);
              distanceMeasurement.setEndLocation(point);
            } else {
              // set the measurement end location and stop listening for mouse movement
              sceneView.setOnMouseMoved(null);
              distanceMeasurement.setEndLocation(point);
            }
          } catch (InterruptedException | ExecutionException e) {
            e.printStackTrace();
          }
        });
      }
    });
  }

  /**
   * Update the measurement's unit system when the combo box option is changed.
   */
  @FXML
  private void changeUnitSystem() {

    distanceMeasurement.setUnitSystem(unitSystemComboBox.getValue());
  }

  /**
   * Stops and releases all resources used in application.
   */
  void terminate() {

    if (sceneView != null) {
      sceneView.dispose();
    }
  }

}

Your browser is no longer supported. Please upgrade your browser for the best experience. See our browser deprecation post for more details.