Determine spatial relationships between two geometries.

Use case
In case of a natural disaster, emergency services can represent the affected areas using polygons. By determining the spatial relationships between these and any other existing features such as populated areas, infrastructure, or natural resources, it is possible to quickly determine which of the existing features might be affected or is in further danger, helping to assess risk and define further action.
How to use the sample
Select one of the three graphics. The tree view will list the relationships the selected graphic has to the other graphic geometries.
How it works
- Get the geometry from two different graphics. In this example the geometry of the selected graphic is compared to the geometry of each unselected graphic.
- Use the methods in
GeometryEngineto check the relationship between the geometries, e.g.contains,disjoint,intersects, etc. If the method returnstrue, the relationship exists.
Relevant API
- Geometry
- GeometryEngine
- GeometryEngine::contains
- GeometryEngine::crosses
- GeometryEngine::disjoint
- GeometryEngine::intersects
- GeometryEngine::overlaps
- GeometryEngine::touches
- GeometryEngine::within
- GeometryType
- Graphic
- Point
- Polygon
- Polyline
Tags
geometries, relationship, spatial analysis
Sample Code
// [WriteFile Name=SpatialRelationships, Category=Geometry]// [Legal]// 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.// [Legal]
#ifdef PCH_BUILD#include "pch.hpp"#endif // PCH_BUILD
// sample headers#include "SpatialRelationships.h"
// ArcGIS Maps SDK headers#include "GeometryEngine.h"#include "Graphic.h"#include "GraphicListModel.h"#include "GraphicsOverlay.h"#include "GraphicsOverlayListModel.h"#include "IdentifyGraphicsOverlayResult.h"#include "Map.h"#include "MapQuickView.h"#include "MapTypes.h"#include "Point.h"#include "Polygon.h"#include "PolygonBuilder.h"#include "Polyline.h"#include "PolylineBuilder.h"#include "SelectionProperties.h"#include "SimpleFillSymbol.h"#include "SimpleLineSymbol.h"#include "SimpleMarkerSymbol.h"#include "SpatialReference.h"#include "SymbolTypes.h"
// Qt headers#include <QFuture>#include <QStringList>#include <QUuid>
// STL headers#include <memory>
using namespace Esri::ArcGISRuntime;
SpatialRelationships::SpatialRelationships(QQuickItem* parent /* = nullptr */): QQuickItem(parent){}
void SpatialRelationships::init(){ // Register the map view for QML qmlRegisterType<MapQuickView>("Esri.Samples", 1, 0, "MapView"); qmlRegisterType<SpatialRelationships>("Esri.Samples", 1, 0, "SpatialRelationshipsSample");}
void SpatialRelationships::componentComplete(){ QQuickItem::componentComplete();
// find QML MapView component m_mapView = findChild<MapQuickView*>("mapView"); m_mapView->setSelectionProperties(SelectionProperties(QColor(Qt::yellow)));
// Create a map using the topographic basemap m_map = new Map(BasemapStyle::ArcGISTopographic, this);
// Set map to map view m_mapView->setMap(m_map);
// Create GraphicsOverlay m_graphicsOverlay = new GraphicsOverlay(this); m_mapView->graphicsOverlays()->append(m_graphicsOverlay);
// Add Graphics addGraphics();
// Set viewpoint m_mapView->setViewpointCenterAsync(geometry_cast<Point>(m_pointGraphic->geometry()), 200000000);
// connect signals connectSignals();}
void SpatialRelationships::addGraphics(){ addPolygonGraphic(); addPolylineGraphic(); addPointGraphic();}
void SpatialRelationships::addPolygonGraphic(){ // create polygon geometry PolygonBuilder polyBuilder(SpatialReference::webMercator()); polyBuilder.addPoint(-5991501.677830, 5599295.131468); polyBuilder.addPoint(-6928550.398185, 2087936.739807); polyBuilder.addPoint(-3149463.800709, 1840803.011362); polyBuilder.addPoint(-1563689.043184, 3714900.452072); polyBuilder.addPoint(-3180355.516764, 5619889.608838); Polygon geom = polyBuilder.toPolygon();
// create symbol SimpleLineSymbol* outline = new SimpleLineSymbol(SimpleLineSymbolStyle::Solid, QColor("green"), 2.0f /*width*/, this); SimpleFillSymbol* sfs = new SimpleFillSymbol(SimpleFillSymbolStyle::ForwardDiagonal, QColor("green"), outline, this);
// create graphic m_polygonGraphic = new Graphic(geom, sfs); m_graphicsOverlay->graphics()->append(m_polygonGraphic);}
void SpatialRelationships::addPolylineGraphic(){ // create poyline geometry PolylineBuilder polyBuilder(SpatialReference::webMercator()); polyBuilder.addPoint(-4354240.726880, -609939.795721); polyBuilder.addPoint(-3427489.245210, 2139422.933233); polyBuilder.addPoint(-2109442.693501, 4301843.057130); polyBuilder.addPoint(-1810822.771630, 7205664.366363); Polyline geom = polyBuilder.toPolyline();
// create symbol SimpleLineSymbol* sls = new SimpleLineSymbol(SimpleLineSymbolStyle::Dash, QColor("red"), 4.0f /*width*/, this);
// create graphic m_polylineGraphic = new Graphic(geom, sls); m_graphicsOverlay->graphics()->append(m_polylineGraphic);}
void SpatialRelationships::addPointGraphic(){ // Create point geometry Point geom(-4487263.495911, 3699176.480377, SpatialReference::webMercator());
// create symbol SimpleMarkerSymbol* sms = new SimpleMarkerSymbol(SimpleMarkerSymbolStyle::Circle, QColor("blue"), 10.0f /*size*/, this);
// create graphic m_pointGraphic = new Graphic(geom, sms, this); m_graphicsOverlay->graphics()->append(m_pointGraphic);}
void SpatialRelationships::connectSignals(){ connect(m_mapView, &MapQuickView::mouseClicked, this, [this](QMouseEvent& mouseEvent) { // identify graphics m_mapView->identifyGraphicsOverlayAsync(m_graphicsOverlay, mouseEvent.position(), 1.0 /*tolerance*/, false /*returnPopupsOnly*/).then(this, [this](IdentifyGraphicsOverlayResult* rawResult) { // Delete rawReslt when we leave scope. auto result = std::unique_ptr<IdentifyGraphicsOverlayResult>(rawResult);
const QList<Graphic*> identifiedGraphics = result->graphics(); if (identifiedGraphics.isEmpty()) return;
// get the first identified graphic Graphic* graphic = identifiedGraphics.at(0);
// select the graphic m_graphicsOverlay->clearSelection(); graphic->setSelected(true);
// get the geometry const Geometry selectedGeometry = graphic->geometry(); const GeometryType selectedGeometryType = selectedGeometry.geometryType();
// reset the output text m_pointRelationships = ""; m_polylineRelationships = ""; m_polygonRelationships = "";
// populate the view with the spatial relationships the selected graphic has to the other graphics // ignore testing relationships between the geometry and itself if (selectedGeometryType != GeometryType::Point) { const QString pointRelationships = getSpatialRelationships(selectedGeometry, m_pointGraphic->geometry()).join(","); m_pointRelationships = QString("Point: %1").arg(pointRelationships); } if (selectedGeometryType != GeometryType::Polyline) { const QString polylineRelationships = getSpatialRelationships(selectedGeometry, m_polylineGraphic->geometry()).join(","); m_polylineRelationships = QString("Polyline: %1").arg(polylineRelationships); } if (selectedGeometryType != GeometryType::Polygon) { const QString polygonRelationships = getSpatialRelationships(selectedGeometry, m_polygonGraphic->geometry()).join(","); m_polygonRelationships = QString("Polygon: %1").arg(polygonRelationships); }
emit relationshipsChanged(); });
});}
// function to return list of relaionshipsQStringList SpatialRelationships::getSpatialRelationships(const Geometry& geom1, const Geometry& geom2){ QStringList relationships; if (GeometryEngine::crosses(geom1, geom2)) relationships.append("CROSSES"); if (GeometryEngine::contains(geom1, geom2)) relationships.append("CONTAINS"); if (GeometryEngine::disjoint(geom1, geom2)) relationships.append("DISJOINT"); if (GeometryEngine::intersects(geom1, geom2)) relationships.append("INTERSECTS"); if (GeometryEngine::overlaps(geom1, geom2)) relationships.append("OVERLAPS"); if (GeometryEngine::touches(geom1, geom2)) relationships.append("TOUCHES"); if (GeometryEngine::within(geom1, geom2)) relationships.append("WITHIN"); return relationships;}// [WriteFile Name=SpatialRelationships, Category=Geometry]// [Legal]// 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.// [Legal]
#ifndef SPATIALRELATIONSHIPS_H#define SPATIALRELATIONSHIPS_H
// ArcGIS Maps SDK headers#include "Geometry.h"
// Qt headers#include <QQuickItem>
namespace Esri::ArcGISRuntime{class Map;class MapQuickView;class Graphic;class GraphicsOverlay;}
class SpatialRelationships : public QQuickItem{ Q_OBJECT
Q_PROPERTY(QString pointRelationships MEMBER m_pointRelationships NOTIFY relationshipsChanged) Q_PROPERTY(QString polygonRelationships MEMBER m_polygonRelationships NOTIFY relationshipsChanged) Q_PROPERTY(QString polylineRelationships MEMBER m_polylineRelationships NOTIFY relationshipsChanged)
public: explicit SpatialRelationships(QQuickItem* parent = nullptr); ~SpatialRelationships() override = default;
void componentComplete() override; static void init();
signals: void relationshipsChanged();
private: Esri::ArcGISRuntime::Map* m_map = nullptr; Esri::ArcGISRuntime::MapQuickView* m_mapView = nullptr; Esri::ArcGISRuntime::GraphicsOverlay* m_graphicsOverlay = nullptr; Esri::ArcGISRuntime::Graphic* m_pointGraphic = nullptr; Esri::ArcGISRuntime::Graphic* m_polylineGraphic = nullptr; Esri::ArcGISRuntime::Graphic* m_polygonGraphic = nullptr; QString m_pointRelationships; QString m_polygonRelationships; QString m_polylineRelationships;
void addGraphics(); void addPointGraphic(); void addPolygonGraphic(); void addPolylineGraphic(); void connectSignals(); QStringList getSpatialRelationships(const Esri::ArcGISRuntime::Geometry& geom1, const Esri::ArcGISRuntime::Geometry& geom2);};
#endif // SPATIALRELATIONSHIPS_H// [WriteFile Name=SpatialRelationships, Category=Geometry]// [Legal]// 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.// [Legal]
import QtQuickimport QtQuick.Windowimport QtQuick.Controlsimport Esri.Samples
SpatialRelationshipsSample { id: rootRectangle clip: true width: 800 height: 600
// add a mapView component MapView { anchors.fill: parent objectName: "mapView"
Component.onCompleted: { // Set the focus on MapView to initially enable keyboard navigation forceActiveFocus(); } }
Rectangle { anchors { fill: relationshipColumn margins: -10 } opacity: 0.85 radius: 5 color: "#e2e2e2" border { color: "darkgray" width: 1 } }
Column { id: relationshipColumn anchors { left: parent.left top: parent.top margins: 15 } spacing: 5
Text { text: "Relationships:" font { pixelSize: 16 bold: true family: "helvetica" } }
Text { id: pointText visible: text.length > 0 font.family: "helvetica" text: pointRelationships }
Text { id: lineText visible: text.length > 0 font.family: "helvetica" text: polylineRelationships }
Text { id: polygonText visible: text.length > 0 font.family: "helvetica" text: polygonRelationships } }}// [Legal]// 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.// [Legal]
// sample headers#include "SpatialRelationships.h"
// ArcGIS Maps SDK headers#include "ArcGISRuntimeEnvironment.h"
// Qt headers#include <QCommandLineParser>#include <QDir>#include <QGuiApplication>#include <QQmlEngine>#include <QQuickView>
// Platform specific headers#ifdef Q_OS_WIN#include <Windows.h>#endif
#define STRINGIZE(x) #x#define QUOTE(x) STRINGIZE(x)
int main(int argc, char *argv[]){ Esri::ArcGISRuntime::ArcGISRuntimeEnvironment::setUseLegacyAuthentication(false); QGuiApplication app(argc, argv); app.setApplicationName(QString("SpatialRelationships"));
// 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 SpatialRelationships::init();
// Initialize application view QQuickView view; view.setResizeMode(QQuickView::SizeRootObjectToView);
QString arcGISRuntimeImportPath = QUOTE(ARCGIS_RUNTIME_IMPORT_PATH);
#if defined(LINUX_PLATFORM_REPLACEMENT) // on some linux platforms the string 'linux' is replaced with 1 // fix the replacement paths which were created QString replaceString = QUOTE(LINUX_PLATFORM_REPLACEMENT); arcGISRuntimeImportPath = arcGISRuntimeImportPath.replace(replaceString, "linux", Qt::CaseSensitive);#endif
// Add the import Path view.engine()->addImportPath(QDir(QCoreApplication::applicationDirPath()).filePath("qml")); // Add the Runtime and Extras path view.engine()->addImportPath(arcGISRuntimeImportPath);
// Set the source view.setSource(QUrl("qrc:/Samples/Geometry/SpatialRelationships/SpatialRelationships.qml"));
view.show();
return app.exec();}