Edit features with feature-linked annotation

View on GitHubSample viewer app

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

Image of edit features with feature-linked annotation

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. That functionality is covered in the sample Generate geodatabase.
  2. Create FeatureLayers from GeodatabaseFeatureTables found in the geodatabase with geodatabase.geodatabaseFeatureTables.
  3. Create AnnotationLayers from GeodatabaseFeatureTables found in the geodatabase with geodatabase.geodatabaseAnnotationTables.
  4. Add the FeatureLayers and AnnotationLayers to the map's operational layers.
  5. Use a DefaultMapViewOnTouchListener to listen for taps on the map to either select address points or parcel polyline features. NOTE: Selection is only enabled for points and straight (signal segment) polylines.
  6. For the address points, a dialog is opened to allow editing of the address number (AD_ADDRESS) and street name (ST_STR_NAM) attributes, which use the expression $feature.AD_ADDRESS + " " + $feature.ST_STR_NAM for annotation.
  7. For the parcel lines, a second tap will change one of the polyline's vertices. Note that the dimension annotation updates according to the expression Round(Length(Geometry($feature), 'feet'), 2).

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

Relevant API

  • AnnotationLayer
  • Feature
  • FeatureLayer
  • Geodatabase

Offline Data

  1. Download the data from ArcGIS Online.
  2. Extract the contents of the downloaded zip file to disk.
  3. Open your command prompt and navigate to the folder where you extracted the contents of the data from step 1.
  4. Push the data into the scoped storage of the sample app:

adb push loudoun_anno.geodatabase /Android/data/com.esri.arcgisruntime.sample.editfeatureswithfeaturelinkedannotation/files/loudoun_anno.geodatabase

About the data

This sample uses data derived from the Loudoun GeoHub

Tags

annotation, attributes, feature-linked annotation, fields

Sample Code

MainActivity.kt
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
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
/*
 * 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.
 *
 */

package com.esri.arcgisruntime.sample.editfeatureswithfeaturelinkedannotation

import android.os.Bundle
import android.util.Log
import android.view.LayoutInflater
import android.view.MotionEvent
import android.widget.Toast
import androidx.appcompat.app.AlertDialog
import androidx.appcompat.app.AppCompatActivity
import com.esri.arcgisruntime.ArcGISRuntimeEnvironment
import com.esri.arcgisruntime.data.Feature
import com.esri.arcgisruntime.data.Geodatabase
import com.esri.arcgisruntime.geometry.*
import com.esri.arcgisruntime.layers.AnnotationLayer
import com.esri.arcgisruntime.layers.FeatureLayer
import com.esri.arcgisruntime.mapping.ArcGISMap
import com.esri.arcgisruntime.mapping.BasemapStyle
import com.esri.arcgisruntime.mapping.Viewpoint
import com.esri.arcgisruntime.mapping.view.DefaultMapViewOnTouchListener
import com.esri.arcgisruntime.mapping.view.MapView
import com.esri.arcgisruntime.sample.editfeatureswithfeaturelinkedannotation.databinding.ActivityMainBinding
import com.esri.arcgisruntime.sample.editfeatureswithfeaturelinkedannotation.databinding.EditAttributeLayoutBinding
import kotlin.math.roundToInt

class MainActivity : AppCompatActivity() {

    private val TAG = MainActivity::class.simpleName

    private var selectedFeature: Feature? = null
    private var selectedFeatureIsPolyline = false

    private val activityMainBinding by lazy {
        ActivityMainBinding.inflate(layoutInflater)
    }

    private val mapView: MapView by lazy {
        activityMainBinding.mapView
    }

    override fun onCreate(savedInstanceState: Bundle?) {
        super.onCreate(savedInstanceState)
        setContentView(activityMainBinding.root)

        // authentication with an API key or named user is required to access basemaps and other
        // location services
        ArcGISRuntimeEnvironment.setApiKey(BuildConfig.API_KEY)

        // NOTE: to be a writable geodatabase, this geodatabase must be generated from a service with a
        // GeodatabaseSyncTask. See the "generate geodatabase" sample to see how to generate a
        // geodatabase

        // create and load geodatabase
        val geodatabase = Geodatabase(getExternalFilesDir(null)?.path + "/loudoun_anno.geodatabase")
        geodatabase.loadAsync()
        geodatabase.addDoneLoadingListener {
            // create feature layers from tables in the geodatabase
            val addressPointFeatureLayer =
                FeatureLayer(geodatabase.getGeodatabaseFeatureTable("Loudoun_Address_Points_1"))
            val parcelLinesFeatureLayer =
                FeatureLayer(geodatabase.getGeodatabaseFeatureTable("ParcelLines_1"))
            // create annotation layers from tables in the geodatabase
            val addressPointsAnnotationLayer =
                AnnotationLayer(geodatabase.getGeodatabaseAnnotationTable("Loudoun_Address_PointsAnno_1"))
            val parcelLinesAnnotationLayer =
                AnnotationLayer(geodatabase.getGeodatabaseAnnotationTable("ParcelLinesAnno_1"))

            // create the map with a light gray canvas basemap
            val map = ArcGISMap(BasemapStyle.ARCGIS_LIGHT_GRAY).apply {
                // add the feature layers to the map
                operationalLayers.add(parcelLinesFeatureLayer)
                operationalLayers.add(addressPointFeatureLayer)
                // add the annotation layers to the map
                operationalLayers.add(parcelLinesAnnotationLayer)
                operationalLayers.add(addressPointsAnnotationLayer)
            }

            mapView.apply {
                // add the map to the map view
                this.map = map

                // set the initial viewpoint to Loudoun, Virginia
                setViewpoint(Viewpoint(39.0204, -77.4159, 2000.0))

                // set on tap behaviour
                onTouchListener =
                    object : DefaultMapViewOnTouchListener(applicationContext, mapView) {
                        override fun onSingleTapUp(e: MotionEvent): Boolean {
                            val screenPoint =
                                android.graphics.Point(e.x.roundToInt(), e.y.roundToInt())
                            selectOrMove(screenPoint)
                            return true
                        }
                    }
            }
        }
    }

    /**
     * Select the nearest feature, or move the point or polyline vertex to the given screen point.
     *
     * @param screenPoint at which to move or select feature
     */
    private fun selectOrMove(screenPoint: android.graphics.Point) {
        // if a feature hasn't been selected
        if (selectedFeature == null) {
            selectFeature(screenPoint)
        } else {
            // convert screen point to map point
            val mapPoint = mapView.screenToLocation(screenPoint)
            // move the feature
            if (selectedFeatureIsPolyline) {
                movePolylineVertex(mapPoint)
            } else {
                movePoint(mapPoint)
            }
        }
    }

    /**
     * Select a feature near the given screen point using identify and, for a point feature, show a
     * dialog to edit attributes. Future taps will call move functions.
     *
     * @param screenPoint at which to select a feature
     */
    private fun selectFeature(screenPoint: android.graphics.Point) {
        // clear any previously selected features
        clearSelection()

        // identify across all layers
        val identifyLayerResultFuture = mapView.identifyLayersAsync(screenPoint, 10.0, false)
        identifyLayerResultFuture.addDoneListener {
            // get the list of result from the future
            val identifyLayerResult = identifyLayerResultFuture.get()
            // for each layer from which an element was identified
            identifyLayerResult.forEach { result ->
                // check if the layer is a feature layer, thereby excluding annotation layers
                (result.layerContent as? FeatureLayer)?.let { featureLayer ->
                    // get a reference to the identified feature
                    selectedFeature = result.elements[0] as? Feature
                    // if the selected feature is a polyline with any part containing more than one segment
                    // (i.e. a curve)
                    (selectedFeature?.geometry as? Polyline)?.parts?.forEach {
                        if (it.pointCount > 2) {
                            // set selected feature to null
                            selectedFeature = null
                            // show message reminding user to select straight (single segment) polylines only
                            Toast.makeText(
                                this,
                                getString(R.string.curved_polylines_message),
                                Toast.LENGTH_SHORT
                            )
                                .show()
                            // return early, effectively disallowing selection of multi segmented polylines
                            return@forEach
                        }
                    }
                    selectedFeature?.let {
                        // select the feature
                        featureLayer.selectFeature(it)
                        when (it.geometry.geometryType) {
                            // when selected feature is a point, show editable attributes
                            GeometryType.POINT -> showEditableAttributes(it)
                            // when selected feature is a polyline,
                            GeometryType.POLYLINE -> selectedFeatureIsPolyline = true
                            else -> Log.e(TAG, "Feature of unexpected geometry type selected")
                        }
                        // return, since a feature has been selected
                        return@addDoneListener
                    }
                }
            }
        }
    }

    /**
     * Create an alert dialog with edit texts to allow editing of the given feature's 'AD_ADDRESS' and
     * 'ST_STR_NAM' attributes.
     *
     * @param selectedFeature whose attributes will be edited
     */
    private fun showEditableAttributes(selectedFeature: Feature) {
        // inflate the edit attribute layout
        val editAttributeLayoutBinding =
            EditAttributeLayoutBinding.inflate(LayoutInflater.from(this))
        // create an alert dialog
        AlertDialog.Builder(this).apply {
            setTitle("Edit feature attribute:")
            setView(editAttributeLayoutBinding.root)
            // populate edit texts with current attribute values
            editAttributeLayoutBinding.addressNumberEditText.setText(selectedFeature.attributes["AD_ADDRESS"].toString())
            editAttributeLayoutBinding.streetEditText.setText(selectedFeature.attributes["ST_STR_NAM"].toString())
            setPositiveButton("OK") { _, _ ->
                // set AD_ADDRESS value to the int from the edit text
                val editAttributeString =
                    editAttributeLayoutBinding.addressNumberEditText.text.toString()
                if (editAttributeString != "") {
                    selectedFeature.attributes["AD_ADDRESS"] = editAttributeString.toInt()
                } else {
                    Toast.makeText(
                        applicationContext,
                        "AD_ADDRESS field must contain an integer!",
                        Toast.LENGTH_LONG
                    ).show()
                }
                // set ST_STR_NAM value to the string from edit text
                selectedFeature.attributes["ST_STR_NAM"] =
                    editAttributeLayoutBinding.streetEditText.text.toString()
                // update the selected feature's feature table
                selectedFeature.featureTable?.updateFeatureAsync(selectedFeature)
            }
            setNegativeButton("Cancel") { _, _ ->
                clearSelection()
            }
        }.show()
    }

    /**
     * Move the currently selected point feature to the given map point, by updating the selected
     * feature's geometry and feature table.
     *
     * @param mapPoint to which the point geometry should be moved to
     */
    private fun movePoint(mapPoint: Point) {
        // set the selected features' geometry to a new map point
        selectedFeature?.geometry = mapPoint
        // update the selected feature's feature table
        selectedFeature?.featureTable?.updateFeatureAsync(selectedFeature)
        // clear selection of point
        clearSelection()
    }

    /**
     * Move the last of the vertex point of the currently selected polyline to the given map point, by updating the selected
     * feature's geometry and feature table.
     *
     * @param mapPoint to which the last point of the polyline should be moved to
     */
    private fun movePolylineVertex(mapPoint: Point) {
        // get the selected feature's geometry as a polyline
        val polyline = selectedFeature?.geometry as Polyline
        // get the nearest vertex to the map point on the selected feature polyline
        val nearestVertex = GeometryEngine.nearestVertex(
            polyline,
            GeometryEngine.project(mapPoint, polyline.spatialReference) as Point
        )
        val polylineBuilder = PolylineBuilder(polyline)
        // get the part of the polyline nearest to the map point
        polylineBuilder.parts[nearestVertex.partIndex.toInt()].apply {
            // remove the nearest point to the map point
            removePoint(nearestVertex.pointIndex.toInt())
            // add the map point as the new point on the polyline
            addPoint(GeometryEngine.project(mapPoint, spatialReference) as Point)
        }
        // set the selected feature's geometry to the new polyline
        selectedFeature?.geometry = polylineBuilder.toGeometry()
        // update the selected feature's feature table
        selectedFeature?.featureTable?.updateFeatureAsync(selectedFeature)
        // clear selection of polyline
        clearSelection()
        selectedFeatureIsPolyline = false
    }

    /**
     * Clear selection from all feature layers.
     */
    private fun clearSelection() {
        mapView.map.operationalLayers.filterIsInstance<FeatureLayer>().forEach { featureLayer ->
            featureLayer.clearSelection()
        }
        selectedFeature = null
    }

    override fun onPause() {
        mapView.pause()
        super.onPause()
    }

    override fun onResume() {
        super.onResume()
        mapView.resume()
    }

    override fun onDestroy() {
        mapView.dispose()
        super.onDestroy()
    }
}

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