Edit features with feature-linked annotation

View inC++QMLView on GitHubSample viewer app

Edit feature attributes which are linked to annotation through an expression.

screenshot

Use case

Annotation is useful for displaying text that you don't want to move or resize when the map is panned or zoomed (unlike labels which will move and resize). Feature-linked annotation will update when a feature attribute referenced by the annotation expression is also updated. Additionally, the position of the annotation will transform to match any transformation to the linked feature's geometry.

How to use the sample

Pan and zoom the map to see that the text on the map is annotation, not labels. Tap one of the address points to update the house number (AD_ADDRESS) and street name (ST_STR_NAM). Tap one of the dashed parcel polylines and tap another location to change its geometry. NOTE: Selection is only enabled for points and straight (single segment) polylines.

The feature-linked annotation will update accordingly.

How it works

  1. Load the geodatabase. NOTE: Read/write geodatabases should normally come from a GeodatabaseSyncTask, but this has been omitted here. That functionality is covered in the sample Generate geodatabase.
  2. Create FeatureLayers from geodatabase feature tables found in the geodatabase with Geodatabase::geodatabaseFeatureTable.
  3. Create AnnotationLayers from geodatabase feature tables found in the geodatabase with Geodatabase::geodatabaseAnnotationTable.
  4. Add the feature layers and annotation layers to the map's operational layers.
  5. Connect to MapQuickView::mouseClicked to capture clicks on the map to either select address points or parcel polyline features. NOTE: Selection is only enabled for points and straight (single segment) polylines.
    • For the address points, a dialog will opened to allow editing of the address number (AD_ADDRESS) and street name (ST_STR_NAM) attributes. A second tap will change the location of the point.
    • For the parcel lines, a second tap will change one of the polyline's vertices.

Both expressions were defined by the data author in ArcGIS Pro using the Arcade expression language.

Relevant API

  • AnnotationLayer
  • Feature
  • FeatureLayer
  • Geodatabase

Offline data

Link Local Location
Loudoun geodatabase <userhome>/ArcGIS/Runtime/Data/geodatabase/loudoun_anno.geodatabase

About the data

This sample uses data derived from the Loudoun GeoHub.

The annotation linked to the point data in this sample is defined by arcade expression $feature.AD_ADDRESS + " " + $feature.ST_STR_NAM. The annotation linked to the parcel polyline data is defined by Round(Length(Geometry($feature), 'feet'), 2).

Tags

annotation, attributes, feature-linked annotation, features, fields

Sample Code

EditFeaturesWithFeatureLinkedAnnotation.cppEditFeaturesWithFeatureLinkedAnnotation.cppEditFeaturesWithFeatureLinkedAnnotation.hEditFeaturesWithFeatureLinkedAnnotation.qml
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
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
// [WriteFile Name=EditFeaturesWithFeatureLinkedAnnotation, Category=EditData]
// [Legal]
// Copyright 2020 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

#include "EditFeaturesWithFeatureLinkedAnnotation.h"

#include "Map.h"
#include "MapQuickView.h"
#include "Geodatabase.h"
#include "AnnotationLayer.h"
#include "FeatureLayer.h"
#include "AnnotationLayer.h"
#include "GeodatabaseFeatureTable.h"
#include "GeometryEngine.h"
#include "PolylineBuilder.h"
#include "PartCollection.h"

// Qt headers
#include <QString>
#include <QFile>
#include <QtCore/qglobal.h>
#include <QTimer>

#include <memory>

#ifdef Q_OS_IOS
#include <QStandardPaths>
#endif // Q_OS_IOS

using namespace Esri::ArcGISRuntime;

// helper method to get cross platform data path
namespace
{
QString defaultDataPath()
{
  QString dataPath;

#ifdef Q_OS_ANDROID
  dataPath = "/sdcard";
#elif defined Q_OS_IOS
  dataPath = QStandardPaths::writableLocation(QStandardPaths::DocumentsLocation);
#else
  dataPath = QDir::homePath();
#endif

  return dataPath;
}
} // namespace

using namespace Esri::ArcGISRuntime;

namespace
{
  // Convenience RAII struct that deletes all pointers in given container.
  struct IdentifyLayerResultsScopedCleanup
  {
    IdentifyLayerResultsScopedCleanup(const QList<IdentifyLayerResult*>& list) : results(list) { }
    ~IdentifyLayerResultsScopedCleanup() { qDeleteAll(results); }
    const QList<IdentifyLayerResult*>& results;
  };
}

EditFeaturesWithFeatureLinkedAnnotation::EditFeaturesWithFeatureLinkedAnnotation(QObject* parent /* = nullptr */):
  QObject(parent),
  s_ad_address(QStringLiteral("AD_ADDRESS")),
  s_st_str_nam(QStringLiteral("ST_STR_NAM"))
{
  constexpr double lat = 39.0204;
  constexpr double lon = -77.4159;
  constexpr double scale = 2256.994353;
  m_map = new Map(BasemapStyle::ArcGISLightGray, this);
  m_map->setInitialViewpoint(Viewpoint(lat, lon, scale));

  const QString dataPath = defaultDataPath() + "/ArcGIS/Runtime/Data/geodatabase/loudoun_anno.geodatabase";

  m_geodatabase = new Geodatabase(dataPath, this);
  connect(m_geodatabase, &Geodatabase::doneLoading, this, &EditFeaturesWithFeatureLinkedAnnotation::onGeodatabaseDoneLoading);

  m_geodatabase->load();
}

EditFeaturesWithFeatureLinkedAnnotation::~EditFeaturesWithFeatureLinkedAnnotation() = default;

void EditFeaturesWithFeatureLinkedAnnotation::init()
{
  // Register the map view for QML
  qmlRegisterType<MapQuickView>("Esri.Samples", 1, 0, "MapView");
  qmlRegisterType<EditFeaturesWithFeatureLinkedAnnotation>("Esri.Samples", 1, 0, "EditFeaturesWithFeatureLinkedAnnotationSample");
}

MapQuickView* EditFeaturesWithFeatureLinkedAnnotation::mapView() const
{
  return m_mapView;
}

// Set the view (created in QML)
void EditFeaturesWithFeatureLinkedAnnotation::setMapView(MapQuickView* mapView)
{
  if (!mapView || mapView == m_mapView)
    return;

  m_mapView = mapView;
  m_mapView->setMap(m_map);

  connect(m_mapView, &MapQuickView::mouseClicked, this, &EditFeaturesWithFeatureLinkedAnnotation::onMouseClicked);
  connect(m_mapView, &MapQuickView::identifyLayersCompleted, this, &EditFeaturesWithFeatureLinkedAnnotation::onIdentifyLayersCompleted);

  emit mapViewChanged();
}

void EditFeaturesWithFeatureLinkedAnnotation::onGeodatabaseDoneLoading(Error error)
{
  if (!error.isEmpty())
    return;

  GeodatabaseFeatureTable* pointFeatureTable = m_geodatabase->geodatabaseFeatureTable("Loudoun_Address_Points_1");
  GeodatabaseFeatureTable* parcelLinesFeatureTable = m_geodatabase->geodatabaseFeatureTable("ParcelLines_1");

  GeodatabaseFeatureTable* addressPointsAnnotationTable = m_geodatabase->geodatabaseAnnotationTable("Loudoun_Address_PointsAnno_1");
  GeodatabaseFeatureTable* parcelLinesAnnotationTable = m_geodatabase->geodatabaseAnnotationTable("ParcelLinesAnno_1");

  // create feature layers from tables in the geodatabase
  m_pointFeatureLayer = new FeatureLayer(pointFeatureTable, this);
  m_parcelLinesFeatureLayer = new FeatureLayer(parcelLinesFeatureTable, this);

  // create annotation layers from tables in the geodatabase
  m_addressPointsAnnotationLayer = new AnnotationLayer(addressPointsAnnotationTable, this);
  m_parcelLinesAnnotationLayer = new AnnotationLayer(parcelLinesAnnotationTable, this);

  // add feature layers to map
  m_map->operationalLayers()->append(m_pointFeatureLayer);
  m_map->operationalLayers()->append(m_parcelLinesFeatureLayer);

  // add annotation layers to map
  m_map->operationalLayers()->append(m_addressPointsAnnotationLayer);
  m_map->operationalLayers()->append(m_parcelLinesAnnotationLayer);
}

void EditFeaturesWithFeatureLinkedAnnotation::onMouseClicked(QMouseEvent mouseEvent)
{
  clearSelection();

  if (m_selectedFeature)
  {
    // move feature to clicked locaiton if already selected
    const Point clickedPoint = m_mapView->screenToLocation(mouseEvent.x(), mouseEvent.y());
    moveFeature(clickedPoint);
  }
  else
  {
    // identify and select feature
    m_mapView->identifyLayers(mouseEvent.x(), mouseEvent.y(), 10, false);
  }
}

void EditFeaturesWithFeatureLinkedAnnotation::onIdentifyLayersCompleted(QUuid, const QList<IdentifyLayerResult*>& identifyResults)
{
  // A convenience wrapper that deletes the contents of identifyResults when we leave scope.
  IdentifyLayerResultsScopedCleanup identifyResultsScopedCleanup(identifyResults);

  for (IdentifyLayerResult* identifyResult : identifyResults)
  {
    if (!identifyResult->geoElements().isEmpty())
    {
      // only perform selections on Feature Layers
      FeatureLayer* featureLayer = dynamic_cast<FeatureLayer*>(identifyResult->layerContent());

      // if cast was successful select features.
      if (featureLayer)
      {
        m_selectedFeature = static_cast<Feature*>(identifyResult->geoElements().at(0));

        // Prevent the feature from being deleted when identifyResultsLock goes out of scope and cleans up identifyResults
        m_selectedFeature->setParent(this);

        const GeometryType selectedFeatureGeomType = m_selectedFeature->geometry().geometryType();

        if (selectedFeatureGeomType == GeometryType::Polyline)
        {
          const Geometry geom = m_selectedFeature->geometry();
          const PolylineBuilder polylineBuilder(geom);

          // if the selected feature is a polyline with any part containing more than one segment
          // (i.e. a curve) do not select it
          if (polylineBuilder.toPolyline().parts().part(0).segmentCount() > 1)
          {
            clearSelection();
            delete m_selectedFeature;
            m_selectedFeature = nullptr;
            return;
          }
        }
        else if (selectedFeatureGeomType == GeometryType::Point)
        {
          // clear string list with attribute values.
          m_addressAndStreetText.clear();

          // update QML text fields with the attributes for the selected point feature
          const QString addressText = m_selectedFeature->attributes()->attributeValue(s_ad_address).toString();
          m_addressAndStreetText.append(addressText);
          const QString streetNameText = m_selectedFeature->attributes()->attributeValue(s_st_str_nam).toString();
          m_addressAndStreetText.append(streetNameText);

          emit addressAndStreetTextChanged();
        }
        featureLayer->selectFeature(m_selectedFeature);
        return;
      }
    }
  }
}

void EditFeaturesWithFeatureLinkedAnnotation::clearSelection()
{
  for (Layer* layer : *m_map->operationalLayers())
  {
    FeatureLayer* featureLayer = dynamic_cast<FeatureLayer*>(layer);
    if (featureLayer)
      featureLayer->clearSelection();
  }
}

void EditFeaturesWithFeatureLinkedAnnotation::moveFeature(Point mapPoint)
{
  const Geometry geom = m_selectedFeature->geometry();

  const Point projectedMapPoint = geometry_cast<Point>(GeometryEngine::project(mapPoint, geom.spatialReference()));
  if (geom.geometryType() == GeometryType::Polyline)
  {
    // get nearest vertex to the map point on the selected polyline
    const ProximityResult nearestVertex = GeometryEngine::nearestVertex(geom, projectedMapPoint);
    const PolylineBuilder polylineBuilder(geom);

    // get part of polyline nearest to map point
    Part* part = polylineBuilder.parts()->part(nearestVertex.partIndex());

    // remove nearest point to map point
    part->removePoint(nearestVertex.pointIndex());

    // add the map point as a new point
    part->addPoint(projectedMapPoint);

    // update the selected feature with the new geometry
    m_selectedFeature->setGeometry(polylineBuilder.toGeometry());
  }
  else if (geom.geometryType() == GeometryType::Point)
  {
    // if the selected feature is a point, change the geometry with the map point
    m_selectedFeature->setGeometry(mapPoint);
  }

  // update the selected feature with the new geometry
  m_selectedFeature->featureTable()->updateFeature(m_selectedFeature);
  clearSelection();
  delete m_selectedFeature;
  m_selectedFeature = nullptr;
}

void EditFeaturesWithFeatureLinkedAnnotation::updateSelectedFeature(const QString& address, const QString& streetName)
{
  if (!m_selectedFeature)
    return;

  // update the two attributes with the inputted text.
  m_selectedFeature->attributes()->replaceAttribute(s_ad_address, address);
  m_selectedFeature->attributes()->replaceAttribute(s_st_str_nam, streetName);
  m_selectedFeature->featureTable()->updateFeature(m_selectedFeature);
}

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