Identify layers

View inJavaKotlinView on GitHubSample viewer app

Identify features in all layers in a map.

Image of identify layers

Use case

IdentifyLayers allows users to tap on a map, returning features at that location across multiple layers. Because some layer types have sublayers, the sample recursively counts results for sublayers within each layer.

How to use the sample

Tap to identify features. An alert will show all layers with features under the tapped location, as well as the number of features.

How it works

  1. The tapped position is passed to MapView.identifyLayersAsync(...)
  2. For each IdentifyLayerResult in the results, features are counted.
    • Note: there is one identify result per layer with matching features; if the feature count is 0, that means a sublayer contains the matching features.

Relevant API

  • IdentifyLayerResult
  • IdentifyLayerResult.sublayerResults
  • MapView.identifyLayersAsync(...)

Additional information

The GeoView supports two methods of identify: identifyLayerAsync(...), which identifies features within a specific layer and identifyLayersAsync(...), which identifies features for all layers in the current view.

Tags

identify, recursion, recursive, sublayers

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
/*
 * 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.identifylayers

import android.os.Bundle
import android.util.Log
import android.view.MotionEvent
import android.widget.Toast
import androidx.appcompat.app.AlertDialog.Builder
import androidx.appcompat.app.AppCompatActivity
import com.esri.arcgisruntime.ArcGISRuntimeEnvironment
import com.esri.arcgisruntime.data.ServiceFeatureTable
import com.esri.arcgisruntime.geometry.Point
import com.esri.arcgisruntime.geometry.SpatialReference
import com.esri.arcgisruntime.layers.ArcGISMapImageLayer
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.IdentifyLayerResult
import com.esri.arcgisruntime.mapping.view.MapView
import com.esri.arcgisruntime.sample.identifylayers.databinding.ActivityMainBinding
import kotlin.math.roundToInt

class MainActivity : AppCompatActivity() {

    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)

        // create a feature layer of damaged property data
        val featureTable = ServiceFeatureTable(getString(R.string.damage_assessment))
        val featureLayer = FeatureLayer(featureTable)

        // create a layer with world cities data
        val mapImageLayer = ArcGISMapImageLayer(getString(R.string.world_cities)).apply {
            addDoneLoadingListener {
                // hide continent and world layers
                subLayerContents[1].isVisible = false
                subLayerContents[2].isVisible = false
            }
        }

        // create a topographic map
        val map = ArcGISMap(BasemapStyle.ARCGIS_TOPOGRAPHIC).apply {
            // add world cities layer
            operationalLayers.add(mapImageLayer)

            // add damaged property data
            operationalLayers.add(featureLayer)
        }

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

            // set the map's initial viewpoint
            setViewpoint(
                Viewpoint(
                    Point(-10977012.785807, 4514257.550369, SpatialReference.create(3857)),
                    68015210.0
                )
            )
            // add a listener to detect taps on the map view
            onTouchListener = object : DefaultMapViewOnTouchListener(this@MainActivity, this) {
                override fun onSingleTapConfirmed(e: MotionEvent?): Boolean {
                    e?.let {
                        val screenPoint = android.graphics.Point(
                            it.x.roundToInt(),
                            it.y.roundToInt()
                        )
                        identifyResult(screenPoint)
                    }
                    return true
                }
            }
        }
    }

    /**
     * Performs an identify on layers at the given screenpoint and calls handleIdentifyResults(...) to process them.
     *
     * @param screenPoint in Android graphic coordinates.
     */
    private fun identifyResult(screenPoint: android.graphics.Point) {

        val identifyLayerResultsFuture = mapView
            .identifyLayersAsync(screenPoint, 12.0, false, 10)

        identifyLayerResultsFuture.addDoneListener {
            try {
                val identifyLayerResults = identifyLayerResultsFuture.get()
                handleIdentifyResults(identifyLayerResults)
            } catch (e: Exception) {
                logError("Error identifying results ${e.message}")
            }
        }
    }

    /**
     * Processes identify results into a string which is passed to showAlertDialog(...).
     *
     * @param identifyLayerResults a list of identify results generated in identifyResult().
     */
    private fun handleIdentifyResults(identifyLayerResults: List<IdentifyLayerResult>) {
        val message = StringBuilder()
        var totalCount = 0
        for (identifyLayerResult in identifyLayerResults) {
            val count = recursivelyCountIdentifyResultsForSublayers(identifyLayerResult)
            val layerName = identifyLayerResult.layerContent.name
            message.append(layerName).append(": ").append(count)

            // add new line character if not the final element in array
            if (identifyLayerResult != identifyLayerResults[identifyLayerResults.size - 1]) {
                message.append("\n")
            }
            totalCount += count
        }

        // if any elements were found show the results, else notify user that no elements were found
        if (totalCount > 0) {
            showAlertDialog(message)
        } else {
            logError("No element found")
        }
    }

    /**
     * Gets a count of the GeoElements in the passed result layer.
     * This method recursively calls itself to descend into sublayers and count their results.
     * @param result from a single layer.
     * @return the total count of GeoElements.
     */
    private fun recursivelyCountIdentifyResultsForSublayers(result: IdentifyLayerResult): Int {
        var subLayerGeoElementCount = 0

        for (sublayerResult in result.sublayerResults) {
            // recursively call this function to accumulate elements from all sublayers
            subLayerGeoElementCount += recursivelyCountIdentifyResultsForSublayers(sublayerResult)
        }

        return subLayerGeoElementCount + result.elements.size
    }

    /**
     * Shows message in an AlertDialog.
     *
     * @param message contains identify results processed into a string.
     */
    private fun showAlertDialog(message: StringBuilder) {
        val alertDialogBuilder = Builder(this)

        // set title
        alertDialogBuilder.setTitle("Number of elements found")

        // set dialog message
        alertDialogBuilder
            .setMessage(message)
            .setCancelable(false)
            .setPositiveButton(getString(R.string.ok)) { dialog, which -> }

        // create alert dialog
        val alertDialog = alertDialogBuilder.create()

        // show the alert dialog
        alertDialog.show()
    }

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

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

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

    /**
     * Log an error to logcat and to the screen via Toast.
     * @param message the text to log.
     */
    private fun logError(message: String?) {
        message?.let {
            Log.e(
                TAG,
                message
            )
            Toast.makeText(this, message, Toast.LENGTH_LONG).show()
        }
    }

    private companion object {
        private val TAG: String = MainActivity::class.java.simpleName
    }
}

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