Sketch on map

View on GitHubSample viewer app

Use the Sketch Editor to edit or sketch a new point, line, or polygon geometry on to a map.

Image of Sketch on map

Use case

A field worker could annotate features of interest on a map (via the GUI) such as location of dwellings (marked as points), geological features (polylines), or areas of glaciation (polygons).

How to use the sample

Choose which geometry type to sketch from one of the available buttons along the bottom of the screen. Choose from points, multipoints, polylines, polygons, freehand polylines, and freehand polygons.

Use the buttons at the top of the screen to: undo or redo change made to the sketch whilst in sketch mode, and to save the sketch to the graphics overlay.

How it works

  1. Create a GeometryEditor and pass it to the MapView with mapView.geometryEditor = geometryEditor.
  2. Set the GeometryEditor.tool to VertexTool() for vertex geometry or FreehandTool() for free hand geometry
  3. Use GeometryEditor.start(GeometryEditorCreationMode) to start sketching.
  4. Check to see if undo and redo are possible during a sketch session using GeometryEditor.canUndo and GeometryEditor.canRedo. If it's possible, use GeometryEditor.undo() and GeometryEditor.redo().
  5. Check if sketch is valid using GeometryBuilder.builder(sketchGeometry).isSketchValid, then allow the sketch to be saved to a GraphicsOverlay.
  6. Get the geometry of the sketch using geometryEditor.geometry.value, and create a new Graphic from that geometry. Add the graphic to the graphics overlay.
  7. To exit the sketch editor, use GeometryEditor.stop().

Relevant API

  • Geometry
  • GeometryEditor
  • GeometryEditorCreationMode
  • Graphic
  • GraphicsOverlay
  • MapView

Tags

draw, edit, sketch

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
/* Copyright 2023 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.arcgismaps.sample.sketchonmap

import android.os.Bundle
import android.util.Log
import android.view.View
import android.widget.AdapterView
import android.widget.ArrayAdapter
import androidx.appcompat.app.AppCompatActivity
import androidx.databinding.DataBindingUtil
import androidx.lifecycle.lifecycleScope
import com.arcgismaps.ApiKey
import com.arcgismaps.ArcGISEnvironment
import com.arcgismaps.Color
import com.arcgismaps.geometry.GeometryBuilder
import com.arcgismaps.geometry.GeometryType
import com.arcgismaps.geometry.Multipoint
import com.arcgismaps.geometry.Point
import com.arcgismaps.geometry.Polygon
import com.arcgismaps.geometry.Polyline
import com.arcgismaps.mapping.ArcGISMap
import com.arcgismaps.mapping.BasemapStyle
import com.arcgismaps.mapping.Viewpoint
import com.arcgismaps.mapping.symbology.SimpleFillSymbol
import com.arcgismaps.mapping.symbology.SimpleFillSymbolStyle
import com.arcgismaps.mapping.symbology.SimpleLineSymbol
import com.arcgismaps.mapping.symbology.SimpleLineSymbolStyle
import com.arcgismaps.mapping.symbology.SimpleMarkerSymbol
import com.arcgismaps.mapping.symbology.SimpleMarkerSymbolStyle
import com.arcgismaps.mapping.view.Graphic
import com.arcgismaps.mapping.view.GraphicsOverlay
import com.arcgismaps.mapping.view.geometryeditor.FreehandTool
import com.arcgismaps.mapping.view.geometryeditor.GeometryEditor
import com.arcgismaps.mapping.view.geometryeditor.VertexTool
import com.esri.arcgismaps.sample.sketchonmap.databinding.SketchOnMapActivityMainBinding
import com.google.android.material.snackbar.Snackbar
import kotlinx.coroutines.launch

class MainActivity : AppCompatActivity() {

    private val activityMainBinding: SketchOnMapActivityMainBinding by lazy {
        DataBindingUtil.setContentView(this, R.layout.sketch_on_map_activity_main)
    }

    private val mapView by lazy {
        activityMainBinding.mapView
    }

    private val selectedGeometryDropdown by lazy {
        activityMainBinding.pointLinePolygonToolbar.selectGeometryDropdown
    }

    // create a symbol for the point graphic
    private val pointSymbol: SimpleMarkerSymbol by lazy {
        SimpleMarkerSymbol(SimpleMarkerSymbolStyle.Square,
            Color(getColor(R.color.point_symbol_color)),
            20f)
    }

    // create a symbol for a line graphic
    private val lineSymbol: SimpleLineSymbol by lazy {
        SimpleLineSymbol(
            SimpleLineSymbolStyle.Solid,
            Color(getColor(R.color.line_symbol_color)),
            4f
        )
    }

    // create a symbol for the fill graphic
    private val fillSymbol: SimpleFillSymbol by lazy {
        SimpleFillSymbol(
            SimpleFillSymbolStyle.Cross,
            Color(getColor(R.color.fill_symbol_color)),
            lineSymbol
        )
    }

    // keep the instance graphic overlay to add graphics on the map
    private var graphicsOverlay: GraphicsOverlay = GraphicsOverlay()

    // keep the instance of the freehand tool
    private val freehandTool: FreehandTool = FreehandTool()

    // keep the instance of the vertex tool
    private val vertexTool: VertexTool = VertexTool()

    // keep the instance to create new geometries, and change existing geometries
    private var geometryEditor: GeometryEditor = GeometryEditor()

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

        // authentication with an API key or named user is
        // required to access basemaps and other location services
        ArcGISEnvironment.apiKey = ApiKey.create(BuildConfig.ACCESS_TOKEN)
        lifecycle.addObserver(mapView)

        // create and add a map with a navigation night basemap style
        mapView.apply {
            map = ArcGISMap(BasemapStyle.ArcGISLightGray)
            setViewpoint(Viewpoint(34.056295, -117.195800, 100000.0))
            graphicsOverlays.add(graphicsOverlay)
        }

        // set MapView's geometry editor to sketch on map
        mapView.geometryEditor = geometryEditor

        // enable/disable the undo button if last event can be undone
        lifecycleScope.launch {
            geometryEditor.canUndo.collect { value ->
                activityMainBinding.pointLinePolygonToolbar.undoButton.isEnabled = value
            }
        }

        // enable/disable the redo button if the last event can be redone
        lifecycleScope.launch {
            geometryEditor.canRedo.collect { value ->
                activityMainBinding.pointLinePolygonToolbar.redoButton.isEnabled = value
            }
        }

        // set up the geometry list dropdown
        selectedGeometryDropdown.apply {
            // set the adapter to the list of geometries
            setAdapter(
                ArrayAdapter(
                    applicationContext,
                    com.esri.arcgismaps.sample.sampleslib.R.layout.custom_dropdown_item,
                    resources.getStringArray(R.array.geometry_list)
                )
            )

            // set the dropdown click listener
            onItemClickListener = AdapterView.OnItemClickListener { _, _, position, _ ->
                // set the GeometryEditorTool and then start the editing process
                geometryEditor.apply {
                    when (position) {
                        0 -> {
                            tool = freehandTool
                            start(GeometryType.Polygon)
                        }
                        1 -> {
                            tool = freehandTool
                            start(GeometryType.Polyline)
                        }
                        2 -> {
                            tool = vertexTool
                            start(GeometryType.Multipoint)
                        }
                        3 -> {
                            tool = vertexTool
                            start(GeometryType.Point)
                        }
                        4 -> {
                            tool = vertexTool
                            start(GeometryType.Polygon)
                        }
                        5 -> {
                            tool = vertexTool
                            start(GeometryType.Polyline)
                        }
                    }
                }
            }
        }
    }

    /**
     * Undo the last event on the GeometryEditor.
     */
    fun undo(view: View) {
        geometryEditor.undo()
    }

    /**
     * Redo the last undone event on the GeometryEditor.
     */
    fun redo(view: View) {
        geometryEditor.redo()
    }

    /**
     * When the stop button is clicked, check that sketch is valid. If so, get the geometry from
     * the sketch, set its symbol and add it to the graphics overlay.
     */
    fun stop(view: View) {
        // get the geometry from sketch editor
        val sketchGeometry = geometryEditor.geometry.value
            ?: return showMessage("Error retrieving geometry")

        if (!GeometryBuilder.builder(sketchGeometry).isSketchValid) {
            return reportNotValid()
        }

        // stops the editing session
        geometryEditor.stop()

        // clear the UI selection
        selectedGeometryDropdown.setText("")
        selectedGeometryDropdown.clearFocus()

        // create a graphic from the sketch editor geometry
        val graphic = Graphic(sketchGeometry).apply {
            // assign a symbol based on geometry type
            symbol = when (sketchGeometry) {
                is Polygon -> fillSymbol
                is Polyline -> lineSymbol
                is Point, is Multipoint -> pointSymbol
                else -> null
            }
        }

        // add the graphic to the graphics overlay
        graphicsOverlay.graphics.add(graphic)
    }

    /**
     * Clear the MapView of all the graphics and reset selections
     */
    fun clear(view: View) {
        geometryEditor.clearGeometry()
        geometryEditor.clearSelection()
        geometryEditor.stop()
        selectedGeometryDropdown.setText("")
        selectedGeometryDropdown.clearFocus()
        showMessage(getString(R.string.cleared_message))
    }

    /**
     * Clear all editing and applied graphics on the map
     */
    fun restart(view: View) {
        graphicsOverlay.graphics.clear()
        geometryEditor.clearGeometry()
        geometryEditor.clearSelection()
        geometryEditor.stop()
        selectedGeometryDropdown.setText("")
        selectedGeometryDropdown.clearFocus()
        showMessage(getString(R.string.restart_message))
    }

    /**
     * Called if sketch is invalid. Reports to user why the sketch was invalid.
     */
    private fun reportNotValid() {
        // get the geometry currently being added to map
        val geometry = geometryEditor.geometry.value ?: return showMessage("Geometry not found")
        // find the geometry type, and set the valid message
        val validIfText: String = when (geometry) {
            is Point -> getString(R.string.invalid_point_message)
            is Multipoint -> getString(R.string.invalid_multipoint_message)
            is Polyline -> getString(R.string.invalid_polyline_message)
            is Polygon -> getString(R.string.invalid_polygon_message)
            else -> getString(R.string.none_selected_message)
        }
        // set the invalid message to the TextView.
        showMessage(validIfText)
    }

    private fun showMessage(message: String) {
        Log.e(localClassName, message)
        Snackbar.make(mapView, message, Snackbar.LENGTH_SHORT).show()
    }
}

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