ArcGIS vector tiled layer (custom style)

View on GitHub
Sample viewer app

Load ArcGIS vector tiled layers using custom styles.

Image of ArcGIS vector tiled layer custom style

Use case

Vector tile basemaps can be created in ArcGIS Pro and published as offline packages or online services. You can create a custom style tailored to your needs and easily apply them to your map. ArcGISVectorTiledLayer has many advantages over traditional raster based basemaps (ArcGISTiledLayer), including smooth scaling between different screen DPIs, smaller package sizes, and the ability to rotate symbols and labels dynamically.

How to use the sample

Pan and zoom to explore the vector tile basemap. Select a theme to see it applied to the vector tile basemap.

How it works

  1. Construct an ArcGISVectorTiledLayer with the URL of a custom style from AGOL.
  2. Alternatively, construct an ArcGISVectorTiledLayer by taking a portal item offline and apply it to an offline vector tile package:
    i. Create an PortalItem using the URL of a custom style.
    ii. Create an ExportVectorTilesTask using the portal item.
    iii. Get the ExportVectorTilesJob using ExportVectorTilesTask.exportStyleResourceCache(withDownloadDirectory:).
    iv. Start the job using ExportVectorTilesJob.start().
    v. Construct an VectorTileCache using the name of the local vector tile package.
    vi. Once the job is complete, construct an ArcGISVectorTiledLayer using the vector tile cache and the ItemResourceCache from the job's result.
  3. Create a Basemap from the ArcGISVectorTiledLayer.
  4. Assign the Basemap to the map's basemap.

Relevant API

  • ArcGISVectorTiledLayer
  • ExportVectorTilesTask
  • ItemResourceCache
  • VectorTileCache

Offline data

  1. Download the data from ArcGIS Online.
  2. Open your command prompt and navigate to the folder where you extracted the contents of the data from step 1.
  3. Execute the following command:

adb push dodge_city.vtpk /Android/data/com.esri.arcgisruntime.sample.arcgisvectortiledlayercustomstyle/files/dodge_city.vtpk

Link Local Location
Dodge City VTPK <sdcard>/Android/data/com.esri.arcgisruntime.sample.arcgisvectortiledlayercustomstyle/files/dodge_city.vtpk

Tags

tiles, vector, vector basemap, vector tile package, vector tiled layer, vector tiles, vtpk

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
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
/*
 *  Copyright 2021 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.arcgisvectortiledlayercustomstyle

import android.content.Context
import android.os.Bundle
import android.view.LayoutInflater
import android.view.View
import android.view.ViewGroup
import android.widget.*
import androidx.appcompat.app.AppCompatActivity
import com.esri.arcgisruntime.ArcGISRuntimeEnvironment
import com.esri.arcgisruntime.concurrent.Job
import com.esri.arcgisruntime.data.VectorTileCache
import com.esri.arcgisruntime.geometry.Point
import com.esri.arcgisruntime.geometry.SpatialReferences
import com.esri.arcgisruntime.layers.ArcGISVectorTiledLayer
import com.esri.arcgisruntime.loadable.LoadStatus
import com.esri.arcgisruntime.mapping.ArcGISMap
import com.esri.arcgisruntime.mapping.ItemResourceCache
import com.esri.arcgisruntime.mapping.Viewpoint
import com.esri.arcgisruntime.mapping.view.MapView
import com.esri.arcgisruntime.portal.Portal
import com.esri.arcgisruntime.portal.PortalItem
import com.esri.arcgisruntime.sample.arcgisvectortiledlayercustomstyle.databinding.ActivityMainBinding
import com.esri.arcgisruntime.sample.arcgisvectortiledlayercustomstyle.databinding.SpinnerItemBinding
import com.esri.arcgisruntime.tasks.vectortilecache.ExportVectorTilesTask

class MainActivity : AppCompatActivity() {

    // A list of portal item IDs for the online layers.
    private var onlineItemIds: Array<String> = arrayOf(
        "1349bfa0ed08485d8a92c442a3850b06",
        "bd8ac41667014d98b933e97713ba8377",
        "02f85ec376084c508b9c8e5a311724fa",
        "1bf0cc4a4380468fbbff107e100f65a5"
    )

    // A list of portal item IDs for the layers which custom style is applied from local resources.
    private var offlineItemIds: Array<String> = arrayOf(
        // A vector tiled layer created by the local VTPK and light custom style.
        "e01262ef2a4f4d91897d9bbd3a9b1075",
        // A vector tiled layer created by the local VTPK and dark custom style.
        "ce8a34e5d4ca4fa193a097511daa8855"
    )

    // The item ID of the currently showing layer.
    private var currentItemID: String = onlineItemIds[0]

    // A dictionary to cache loaded vector tiled layers.
    private var vectorTiledLayersMap: MutableMap<String, ArcGISVectorTiledLayer> = mutableMapOf()

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

    private val spinner: Spinner by lazy {
        activityMainBinding.spinner
    }

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


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

        // Set the map to be displayed in the layout's MapView
        mapView.map = ArcGISMap()

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

        // Set the currentItemID to default layer.
        currentItemID = onlineItemIds[0]

        // Sets up the spinner to change the selected Vector Styled Layer.
        setUpSpinner()
    }

    /**
     * Displays the layer of the given [itemID].
     */
    private fun showSelectedItem(itemID: String) {
        currentItemID = itemID
        val vectorTiledLayer: ArcGISVectorTiledLayer

        // Checks if the layer has been cached.
        when {
            vectorTiledLayersMap.contains(itemID) -> {
                vectorTiledLayer = vectorTiledLayersMap.getValue(itemID)
            }
            onlineItemIds.contains(itemID) -> {
                // Retrieve the layer from online.
                val portalItem = PortalItem(Portal("https://www.arcgis.com"), itemID)
                vectorTiledLayer = ArcGISVectorTiledLayer(portalItem)
                // Adds the retrieved layer to the mutable map for cache.
                vectorTiledLayersMap[itemID] = vectorTiledLayer
            }
            else -> {
                // Load the layer using offline Vector Tiles.
                checkOfflineItemCache(itemID)
                return
            }
        }

        // OnlineItemIDs uses WebMercator as a spatial ref.
        val viewpoint = Viewpoint(
            Point(1990591.559979, 794036.007991, SpatialReferences.getWebMercator()),
            100000000.0
        )
        setMap(vectorTiledLayer, viewpoint)
    }

    /**
     *  Checks local cache for local cache files using the [itemID].
     *  If not, it calls loadLayerWithOfflineCustomStyle([itemID]) to retrieve the cache files.
     */
    private fun checkOfflineItemCache(itemID: String) {

        val portalItem = PortalItem(Portal("https://www.arcgis.com"), itemID)
        val itemResourceCache =
            ItemResourceCache(getExternalFilesDir(null)?.path + "/" + portalItem.itemId)
        itemResourceCache.addDoneLoadingListener {
            if (itemResourceCache.loadStatus == LoadStatus.LOADED) {
                setResourceAndVectorTileCache(itemResourceCache)
            } else {
                loadLayerWithOfflineCustomStyle(itemID)
            }
        }
        itemResourceCache.loadAsync()
    }

    /**
     * Retrieves the style resource files using [itemID] and caches it to the local device.
     */
    private fun loadLayerWithOfflineCustomStyle(itemID: String) {

        // Retrieve the layer from online.
        val portalItem = PortalItem(Portal("https://www.arcgis.com"), itemID)
        val task = ExportVectorTilesTask(portalItem)

        // Create job using portalItem ID and .vtpk path to retrieve the itemResourceCache
        val exportVectorTilesJob =
            task.exportStyleResourceCache(getExternalFilesDir(null)?.path + "/" + portalItem.itemId)
        exportVectorTilesJob.addJobDoneListener {
            if (exportVectorTilesJob.status == Job.Status.SUCCEEDED) {
                setResourceAndVectorTileCache(exportVectorTilesJob.result.itemResourceCache)
            } else {
                Toast.makeText(
                    this,
                    "Error reading cache: " + exportVectorTilesJob.error.message,
                    Toast.LENGTH_LONG
                ).show()
            }
        }
        exportVectorTilesJob.start()

    }

    /**
     * Sets up an ArcGISVectorTiledLayer using the [itemResourceCache]
     * for the setMap() function.
     */
    private fun setResourceAndVectorTileCache(itemResourceCache: ItemResourceCache) {
        //Loads the vector tile layer cache.
        val vectorTileCache = VectorTileCache(getExternalFilesDir(null)?.path + "/dodge_city.vtpk")
        vectorTileCache.loadAsync()
        vectorTileCache.addDoneLoadingListener {
            if (vectorTileCache.loadStatus == LoadStatus.LOADED) {
                // Loads the layer based on the vector tile cache and the style resource.
                val layer = ArcGISVectorTiledLayer(vectorTileCache, itemResourceCache)
                layer.addDoneLoadingListener {
                    if (layer.loadStatus != LoadStatus.LOADED) {
                        Toast.makeText(
                            applicationContext,
                            layer.loadError.message + ": " + layer.loadError.additionalMessage,
                            Toast.LENGTH_SHORT
                        ).show()
                    }
                }

                // OfflineItemIDs uses WGS-84 as a spatial ref.
                val viewpoint =
                    Viewpoint(Point(-100.01766, 37.76528, SpatialReferences.getWgs84()), 100000.0)
                setMap(layer, viewpoint)
            } else
                Toast.makeText(
                    applicationContext,
                    vectorTileCache.loadError.message + ": " + vectorTileCache.loadError.additionalMessage,
                    Toast.LENGTH_SHORT
                ).show()
        }
    }

    /**
     * Set the map using the [layer] and the [viewpoint].
     */
    private fun setMap(layer: ArcGISVectorTiledLayer, viewpoint: Viewpoint) {
        // Clears the existing basemap layer
        mapView.map.basemap.baseLayers.clear()

        // Adds the new vector tiled layer to the basemap.
        mapView.map.basemap.baseLayers.add(layer)

        //Set viewpoint without animation.
        mapView.setViewpoint(viewpoint)
    }

    /**
     * Sets the adapter and listens for a item selection to update the
     * MapView with the selected layer.
     */
    private fun setUpSpinner() {
        val customDropDownAdapter = CustomSpinnerAdapter(this)
        spinner.adapter = customDropDownAdapter
        spinner.onItemSelectedListener = object : AdapterView.OnItemSelectedListener {
            override fun onItemSelected(
                parent: AdapterView<*>?,
                view: View?,
                position: Int,
                id: Long
            ) {

                // Sets the selected itemID to either the Online/Custom ID.
                // Position 4 or 5 in the spinner are the custom (offline) style layers.
                currentItemID = when (position) {
                    4 -> {
                        // Custom style 1 - Dodge City OSM - Light
                        offlineItemIds[0]
                    }
                    5 -> {
                        // Custom style 2 - Dodge City OSM - Dark
                        offlineItemIds[1]
                    }
                    else -> {
                        // Else use the online vector styles
                        onlineItemIds[position]
                    }
                }
                showSelectedItem(currentItemID)
            }

            override fun onNothingSelected(parent: AdapterView<*>?) {
                //Keeps the current selected vector style.
            }
        }
    }

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

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

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

    /**
     * Custom adapter to set and control the spinner.
     * [context] is used to help render the view
     */
    class CustomSpinnerAdapter(private val context: Context) : BaseAdapter() {

        // Inflates each row of the adapter.
        private val inflater: LayoutInflater =
            context.getSystemService(Context.LAYOUT_INFLATER_SERVICE) as LayoutInflater

        override fun getView(position: Int, convertView: View?, parent: ViewGroup?): View {
            val spinnerItemBinding = SpinnerItemBinding.inflate(inflater)
            val view: View
            val itemHolder: ItemHolder
            if (convertView == null) {
                view = spinnerItemBinding.root
                itemHolder = ItemHolder(view)
                view.tag = itemHolder
            } else {
                view = convertView
                itemHolder = view.tag as ItemHolder
            }
            // Sets the TextView to the style name.
            itemHolder.layerText.text =
                context.resources.getStringArray(R.array.style_names)[position]

            // Gets the drawable style associated with the position.
            val id = context.resources.getIdentifier(
                context.resources.getStringArray(R.array.style_drawable_names)[position],
                "drawable",
                context.packageName
            )
            // Sets the retrieved drawable as the background of the colorView.
            itemHolder.colorView.setBackgroundResource(id)

            return view
        }

        override fun getItem(position: Int): Any {
            return context.resources.getStringArray(R.array.style_names)[position]
        }

        override fun getCount(): Int {
            return context.resources.getStringArray(R.array.style_names).size
        }

        override fun getItemId(position: Int): Long {
            return position.toLong()
        }

        private class ItemHolder(row: View?) {
            val layerText: TextView = row?.findViewById(R.id.text) as TextView
            val colorView: View = row?.findViewById(R.id.colorView) as View
        }

    }
}

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