Measure distances between two points in 3D.

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
- Create an
AnalysisOverlayobject and add it to the analysis overlay collection of theSceneViewobject. - Specify the start location and end location to create a
LocationDistanceMeasurementobject. Initially, the start and end locations can be the same point. - Add the location distance measurement analysis to the analysis overlay.
- The
measurementChangedsignal will trigger if the distances change. You can get the new values for thedirectDistance,horizontalDistance, andverticalDistancefrom theMeasurementChangedobject returned by the signal.
Relevant API
- AnalysisOverlay
- LocationDistanceMeasurement
- MeasurementChanged
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
// [WriteFile Name=DistanceMeasurementAnalysis, Category=Analysis]// [Legal]// Copyright 2022 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.// [Legal]
#ifdef PCH_BUILD#include "pch.hpp"#endif // PCH_BUILD
// sample headers#include "DistanceMeasurementAnalysis.h"
// ArcGIS Maps SDK headers#include "AnalysisListModel.h"#include "AnalysisOverlay.h"#include "AnalysisOverlayListModel.h"#include "ArcGISSceneLayer.h"#include "ArcGISTiledElevationSource.h"#include "Camera.h"#include "CoreTypes.h"#include "Distance.h"#include "ElevationSourceListModel.h"#include "LayerListModel.h"#include "LinearUnit.h"#include "LocationDistanceMeasurement.h"#include "MapTypes.h"#include "Point.h"#include "Scene.h"#include "SceneQuickView.h"#include "SpatialReference.h"#include "Surface.h"#include "Viewpoint.h"
// Qt headers#include <QFuture>#include <QUuid>
using namespace Esri::ArcGISRuntime;
DistanceMeasurementAnalysis::DistanceMeasurementAnalysis(QObject* parent /* = nullptr */): QObject(parent), m_scene(new Scene(BasemapStyle::ArcGISTopographic, this)){ // create a new elevation source from Terrain3D REST service ArcGISTiledElevationSource* elevationSource = new ArcGISTiledElevationSource( QUrl("https://elevation3d.arcgis.com/arcgis/rest/services/WorldElevation3D/Terrain3D/ImageServer"), this);
// add the elevation source to the scene to display elevation m_scene->baseSurface()->elevationSources()->append(elevationSource);
// Add a Scene Layer ArcGISSceneLayer* sceneLayer = new ArcGISSceneLayer(QUrl("https://tiles.arcgis.com/tiles/P3ePLMYs2RVChkJx/arcgis/rest/services/Buildings_Brest/SceneServer/layers/0"), this); sceneLayer->setAltitudeOffset(1); // The elevation source is a very fine resolution so we raise the scene layer slightly so it does not clip the surface
m_scene->operationalLayers()->append(sceneLayer);}
DistanceMeasurementAnalysis::~DistanceMeasurementAnalysis() = default;
void DistanceMeasurementAnalysis::init(){ // Register classes for QML qmlRegisterType<SceneQuickView>("Esri.Samples", 1, 0, "SceneView"); qmlRegisterType<DistanceMeasurementAnalysis>("Esri.Samples", 1, 0, "DistanceMeasurementAnalysisSample");}
SceneQuickView* DistanceMeasurementAnalysis::sceneView() const{ return m_sceneView;}
// Set the view (created in QML)void DistanceMeasurementAnalysis::setSceneView(SceneQuickView* sceneView){ if (!sceneView || sceneView == m_sceneView) return;
m_sceneView = sceneView; m_sceneView->setArcGISScene(m_scene); emit sceneViewChanged();
// Add Analysis Overlay AnalysisOverlay* analysisOverlay = new AnalysisOverlay(this); m_sceneView->analysisOverlays()->append(analysisOverlay);
// Create and add the LocationDistanceMeasurement const Point startLocation(-4.494677, 48.384472, 24.772694, SpatialReference::wgs84()); const Point endLocation(-4.495646, 48.384377, 58.501115, SpatialReference::wgs84()); m_distanceAnalysis = new LocationDistanceMeasurement(startLocation, endLocation, this); m_distanceAnalysis->setUnitSystem(UnitSystem::Metric); analysisOverlay->analyses()->append(m_distanceAnalysis);
// Set initial viewpoint constexpr double distance = 400.0; constexpr double pitch = 45.0; constexpr double heading = 0.0; constexpr double roll = 0.0; const Camera initCamera(startLocation, distance, heading, pitch, roll); const Viewpoint initViewpoint(startLocation, distance, initCamera); m_scene->setInitialViewpoint(initViewpoint);
connectSignals();}
void DistanceMeasurementAnalysis::connectSignals(){ // connect to signal to obtain updated distances connect(m_distanceAnalysis, &LocationDistanceMeasurement::measurementChanged, this, [this](const Distance& directDistance, const Distance& horizontalDistance, const Distance& verticalDistance) { m_directDistance = QString::number(directDistance.value(), 'f', 2) + QString(" %1").arg(directDistance.unit().abbreviation()); m_horizontalDistance = QString::number(horizontalDistance.value(), 'f', 2) + QString(" %1").arg(horizontalDistance.unit().abbreviation()); m_verticalDistance = QString::number(verticalDistance.value(), 'f', 2) + QString(" %1").arg(verticalDistance.unit().abbreviation()); emit directDistanceChanged(); emit horizontalDistanceChanged(); emit verticalDistanceChanged(); });
// connect to mouse signals to update the analysis
// When the mouse is pressed and held, start updating the distance analysis end point connect(m_sceneView, &SceneQuickView::mousePressedAndHeld, this, [this](QMouseEvent& mouseEvent) { m_isPressAndHold = true; m_sceneView->screenToLocationAsync(mouseEvent.position().x(), mouseEvent.position().y()).then(this, [this](const Point& pt) { onScreenToLocationCompleted_(pt); }); });
// When the mouse is released... connect(m_sceneView, &SceneQuickView::mouseReleased, this, [this](QMouseEvent& mouseEvent) { // Check if the mouse was released from a pan gesture if (m_isNavigating) { m_isNavigating = false; return; }
// Ignore if Right click if (mouseEvent.button() == Qt::RightButton) return;
// If pressing and holding, do nothing if (m_isPressAndHold) m_isPressAndHold = false; // Else get the location from the screen coordinates else m_sceneView->screenToLocationAsync(mouseEvent.position().x(), mouseEvent.position().y()).then(this, [this](const Point& pt) { onScreenToLocationCompleted_(pt); }); });
// Update the distance analysis when the mouse moves if it is a press and hold movement connect(m_sceneView, &SceneQuickView::mouseMoved, this, [this](QMouseEvent& mouseEvent) { if (m_isPressAndHold) m_sceneView->screenToLocationAsync(mouseEvent.position().x(), mouseEvent.position().y()).then(this, [this](const Point& pt) { onScreenToLocationCompleted_(pt); }); });
// Set a flag when mousePressed signal emits connect(m_sceneView, &SceneQuickView::mousePressed, this, [this] { m_isNavigating = false; });
// Set a flag when viewpointChanged signal emits connect(m_sceneView, &SceneQuickView::viewpointChanged, this, [this] { m_isNavigating = true; });}
void DistanceMeasurementAnalysis::onScreenToLocationCompleted_(const Point& pt){ // If it was from a press and hold, update the end location if (m_isPressAndHold) m_distanceAnalysis->setEndLocation(pt); // Else if it was a normal mouse click (press and release), update the start location else m_distanceAnalysis->setStartLocation(pt);}
void DistanceMeasurementAnalysis::setUnits(const QString& unitName){ if (!m_distanceAnalysis) return;
if (unitName == "Metric") m_distanceAnalysis->setUnitSystem(UnitSystem::Metric); else m_distanceAnalysis->setUnitSystem(UnitSystem::Imperial);}
QString DistanceMeasurementAnalysis::directDistance() const{ return m_directDistance;}
QString DistanceMeasurementAnalysis::horizontalDistance() const{ return m_horizontalDistance;}
QString DistanceMeasurementAnalysis::verticalDistance() const{ return m_verticalDistance;}// [WriteFile Name=DistanceMeasurementAnalysis, Category=Analysis]// [Legal]// Copyright 2022 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.// [Legal]
#ifndef DISTANCEMEASUREMENTANALYSIS_H#define DISTANCEMEASUREMENTANALYSIS_H
// Qt headers#include <QObject>
namespace Esri::ArcGISRuntime{class LocationDistanceMeasurement;class Point;class Scene;class SceneQuickView;}
Q_MOC_INCLUDE("SceneQuickView.h");
class DistanceMeasurementAnalysis : public QObject{ Q_OBJECT
Q_PROPERTY(Esri::ArcGISRuntime::SceneQuickView* sceneView READ sceneView WRITE setSceneView NOTIFY sceneViewChanged) Q_PROPERTY(QString directDistance READ directDistance NOTIFY directDistanceChanged) Q_PROPERTY(QString horizontalDistance READ horizontalDistance NOTIFY horizontalDistanceChanged) Q_PROPERTY(QString verticalDistance READ verticalDistance NOTIFY verticalDistanceChanged)
public: explicit DistanceMeasurementAnalysis(QObject* parent = nullptr); ~DistanceMeasurementAnalysis() override;
static void init(); Q_INVOKABLE void setUnits(const QString& unitName);
signals: void sceneViewChanged(); void directDistanceChanged(); void horizontalDistanceChanged(); void verticalDistanceChanged();
private: Esri::ArcGISRuntime::SceneQuickView* sceneView() const; void setSceneView(Esri::ArcGISRuntime::SceneQuickView* sceneView); void onScreenToLocationCompleted_(const Esri::ArcGISRuntime::Point& pt);
Esri::ArcGISRuntime::Scene* m_scene = nullptr; Esri::ArcGISRuntime::SceneQuickView* m_sceneView = nullptr; Esri::ArcGISRuntime::LocationDistanceMeasurement* m_distanceAnalysis = nullptr; QString m_directDistance; QString m_horizontalDistance; QString m_verticalDistance; bool m_isPressAndHold = false; bool m_isNavigating = false; QString directDistance() const; QString horizontalDistance() const; QString verticalDistance() const; void connectSignals();};
#endif // DISTANCEMEASUREMENTANALYSIS_H// [WriteFile Name=DistanceMeasurementAnalysis, Category=Analysis]// [Legal]// Copyright 2022 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.// [Legal]
import QtQuickimport QtQuick.Controlsimport Esri.Samples
Item {
SceneView { id: view anchors.fill: parent
Component.onCompleted: { // Set and keep the focus on SceneView to enable keyboard navigation forceActiveFocus(); } }
// Declare the C++ instance which creates the scene etc. and supply the view DistanceMeasurementAnalysisSample { id: model sceneView: view }
Rectangle { anchors { fill: resultsColumn margins: -5 } color: "black" opacity: 0.5 radius: 5 }
Column { id: resultsColumn anchors { left: parent.left top: parent.top margins: 10 } spacing: 5
Row { spacing: 5 Text { text: "Direct Distance:" color: "white" } Text { id: directDistanceText color: "white" text: model.directDistance } } Row { spacing: 5 Text { text: "Vertical Distance:" color: "white" } Text { id: verticalDistanceText color: "white" text: model.verticalDistance } } Row { spacing: 5 Text { text: "Horizontal Distance:" color: "white" } Text { id: horizontalDistanceText color: "white" text: model.horizontalDistance } } Row { id: row spacing: 5 Text { text: "Unit System:" color: "white" } ComboBox { id: comboBox model: ["Metric", "Imperial"] onCurrentTextChanged: model.setUnits(currentText); } } }}// [Legal]// Copyright 2022 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.// [Legal]
// sample headers#include "DistanceMeasurementAnalysis.h"
// ArcGIS Maps SDK headers#include "ArcGISRuntimeEnvironment.h"
// Qt headers#include <QCommandLineParser>#include <QDir>#include <QGuiApplication>#include <QQmlApplicationEngine>#include <QSurfaceFormat>
// Platform specific headers#ifdef Q_OS_WIN#include <Windows.h>#endif
int main(int argc, char *argv[]){ Esri::ArcGISRuntime::ArcGISRuntimeEnvironment::setUseLegacyAuthentication(false);#if defined(Q_OS_LINUX) && !defined(Q_OS_ANDROID) // Linux requires 3.2 OpenGL Context // in order to instance 3D symbols QSurfaceFormat fmt = QSurfaceFormat::defaultFormat(); fmt.setVersion(3, 2); QSurfaceFormat::setDefaultFormat(fmt);#endif
QGuiApplication app(argc, argv); app.setApplicationName(QString("DistanceMeasurementAnalysis"));
// Use of ArcGIS location services, such as basemap styles, geocoding, and routing services, // requires an access token. For more information see // https://links.esri.com/arcgis-runtime-security-auth.
// The following methods grant an access token:
// 1. User authentication: Grants a temporary access token associated with a user's ArcGIS account. // To generate a token, a user logs in to the app with an ArcGIS account that is part of an // organization in ArcGIS Online or ArcGIS Enterprise.
// 2. API key authentication: Get a long-lived access token that gives your application access to // ArcGIS location services. Go to the tutorial at https://links.esri.com/create-an-api-key. // Copy the API Key access token.
const QString accessToken = QString("");
if (accessToken.isEmpty()) { qWarning() << "Use of ArcGIS location services, such as the basemap styles service, requires" << "you to authenticate with an ArcGIS account or set the API Key property."; } else { Esri::ArcGISRuntime::ArcGISRuntimeEnvironment::setApiKey(accessToken); }
// Initialize the sample DistanceMeasurementAnalysis::init();
// Initialize application view QQmlApplicationEngine engine; // Add the import Path engine.addImportPath(QDir(QCoreApplication::applicationDirPath()).filePath("qml"));
#ifdef ARCGIS_RUNTIME_IMPORT_PATH_2 engine.addImportPath(ARCGIS_RUNTIME_IMPORT_PATH_2);#endif
// Set the source engine.load(QUrl("qrc:/Samples/Analysis/DistanceMeasurementAnalysis/main.qml"));
return app.exec();}// Copyright 2022 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.
import QtQuick.Controlsimport Esri.Samples
ApplicationWindow { visible: true width: 800 height: 600
DistanceMeasurementAnalysis { anchors.fill: parent }}