Play KML tour

View on GitHubSample viewer app

Play tours in KML files.

Image of play KML tour

Use case

KML, the file format used by Google Earth, supports creating tours, which can control the viewpoint of the scene, hide and show content, and play audio. Tours allow you to easily share tours of geographic locations, which can be augmented with rich multimedia. Runtime allows you to consume these tours using a simple API.

How to use the sample

The sample will load the KMZ file from ArcGIS Online. When a tour is found, the Play button will be enabled. Use Play and Pause to control the tour. When you're ready to show the tour, use the reset button to return the tour to the unplayed state.

How it works

  1. Create a KmlDataSet from the local kmz file and instantiate a layer from it with KmlLayer(kmlDataSet).
  2. Create the KML tour controller. Wire up the buttons to the KmlTourController.play(), KmlTourController.pause(), and KmlTourController.reset() methods.
  3. Explore the tree of KML content to find the first KML tour. Once a tour is found, provide it to the KML tour controller.

Relevant API

  • KmlTour
  • KmlTourController
  • KmlTourController.pause()
  • KmlTourController.play()
  • KmlTourController.reset()

About the data

This sample uses a custom tour from ArcGIS Online. When you play the tour, you'll go through a audio journey through some of Esri's offices.

Additional information

See Touring in KML in Keyhole Markup Language for more information.

Tags

animation, interactive, KML, narration, pause, play, story, tour

Sample Code

MainActivity.ktMainActivity.ktDownloadActivity.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
/* 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.playkmltour

import android.os.Bundle
import android.util.Log
import androidx.appcompat.app.AppCompatActivity
import androidx.appcompat.content.res.AppCompatResources
import androidx.databinding.DataBindingUtil
import androidx.lifecycle.lifecycleScope
import com.arcgismaps.ApiKey
import com.arcgismaps.ArcGISEnvironment
import com.arcgismaps.mapping.ArcGISScene
import com.arcgismaps.mapping.ArcGISTiledElevationSource
import com.arcgismaps.mapping.BasemapStyle
import com.arcgismaps.mapping.Surface
import com.arcgismaps.mapping.Viewpoint
import com.arcgismaps.mapping.ViewpointType
import com.arcgismaps.mapping.kml.KmlContainer
import com.arcgismaps.mapping.kml.KmlDataset
import com.arcgismaps.mapping.kml.KmlNode
import com.arcgismaps.mapping.kml.KmlTour
import com.arcgismaps.mapping.kml.KmlTourController
import com.arcgismaps.mapping.kml.KmlTourStatus
import com.arcgismaps.mapping.layers.KmlLayer
import com.esri.arcgismaps.sample.playkmltour.databinding.PlayKmlTourActivityMainBinding
import com.google.android.material.snackbar.Snackbar
import kotlinx.coroutines.delay
import kotlinx.coroutines.launch
import java.io.File
import kotlin.math.roundToInt


class MainActivity : AppCompatActivity() {

    private val provisionPath: String by lazy {
        getExternalFilesDir(null)?.path.toString() + File.separator + getString(R.string.play_kml_tour_app_name)
    }

    // set up data binding for the activity
    private val activityMainBinding: PlayKmlTourActivityMainBinding by lazy {
        DataBindingUtil.setContentView(this, R.layout.play_kml_tour_activity_main)
    }

    private val sceneView by lazy {
        activityMainBinding.sceneView
    }

    private val playPauseButton by lazy {
        activityMainBinding.playPauseButton
    }

    private val resetTourButton by lazy {
        activityMainBinding.resetTourButton
    }

    private val tourStatusTV by lazy {
        activityMainBinding.tourStatusTV
    }

    private val tourProgressBar by lazy {
        activityMainBinding.tourProgressBar
    }

    private var initialViewpoint: Viewpoint? = null

    private val kmlTourController = KmlTourController()

    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(sceneView)


        // add elevation data
        val surface = Surface().apply {
            elevationSources.add(ArcGISTiledElevationSource(getString(R.string.world_terrain_service)))
        }

        // create a scene and set the surface
        sceneView.scene = ArcGISScene(BasemapStyle.ArcGISImagery).apply {
            baseSurface = surface
        }

        // add a KML layer from a KML dataset with a KML tour
        val kmlDataset = KmlDataset(provisionPath + getString(R.string.kml_tour_path))
        val kmlLayer = KmlLayer(kmlDataset)

        // add the layer to the scene view's operational layers
        sceneView.scene?.operationalLayers?.add(kmlLayer)

        // load the KML layer
        lifecycleScope.launch {
            kmlLayer.load().onFailure {
                showError(it.message.toString())
            }.onSuccess {
                // get the first loaded KML tour
                val kmlTour = findFirstKMLTour(kmlDataset.rootNodes)
                if (kmlTour == null) {
                    showError("Cannot find KML tour in dataset")
                    return@onSuccess
                }

                // collect changes in KML tour status
                collectKmlTourStatus(kmlTour)

                // set the KML tour to the controller
                kmlTourController.tour = kmlTour
            }
        }

        resetTourButton.setOnClickListener {
            // set tour to the initial viewpoint
            initialViewpoint?.let { sceneView.setViewpoint(it) }
            // reset tour controller
            kmlTourController.reset()
        }

        playPauseButton.setOnClickListener {
            // button was clicked when tour was playing
            if (kmlTourController.tour?.status?.value == KmlTourStatus.Playing)
            // pause KML tour
                kmlTourController.pause()
            else
            // play KML tour
                kmlTourController.play()
        }
    }

    /**
     * Recursively searches for the first KML tour in a list of [kmlNodes].
     * Returns the first [KmlTour], or null if there are no tours.
     */
    private fun findFirstKMLTour(kmlNodes: List<KmlNode>): KmlTour? {
        kmlNodes.forEach { node ->
            if (node is KmlTour)
                return node
            else if (node is KmlContainer)
                return findFirstKMLTour(node.childNodes)
        }
        return null
    }

    /**
     * Collects KmlTourStatus events from the [kmlTour] and then calls
     * showKmlTourStatus()
     */
    private fun collectKmlTourStatus(kmlTour: KmlTour) = lifecycleScope.launch {
        kmlTour.status.collect { kmlTourStatus ->
            when (kmlTourStatus) {
                KmlTourStatus.Completed -> {
                    showKmlTourStatus("Completed", isResetEnabled = false, isPlayingTour = false)
                }
                KmlTourStatus.Initialized -> {
                    showKmlTourStatus("Initialized", isResetEnabled = false, isPlayingTour = false)
                }
                KmlTourStatus.Paused -> {
                    showKmlTourStatus("Paused", isResetEnabled = true, isPlayingTour = false)
                }
                KmlTourStatus.Playing -> {
                    showKmlTourStatus("Playing", isResetEnabled = true, isPlayingTour = true)
                    // set the tour's initial viewpoint
                    if (initialViewpoint == null) {
                        initialViewpoint = sceneView.getCurrentViewpoint(
                            ViewpointType.BoundingGeometry
                        )
                    }
                }
                else -> {}
            }
        }
    }

    /**
     * Displays the KML tour status using the [kmlTourStatus], display [resetTourButton]
     * if [isResetEnabled] and set [playPauseButton] based on [isPlayingTour].
     */
    private fun showKmlTourStatus(
        kmlTourStatus: String,
        isResetEnabled: Boolean,
        isPlayingTour: Boolean
    ) {
        // set the KML tour status
        tourStatusTV.text = String.format("Tour status: %s", kmlTourStatus)

        // enable the buttons
        resetTourButton.isEnabled = isResetEnabled
        playPauseButton.isEnabled = true

        // show pause button if true
        if (isPlayingTour) {
            playPauseButton.apply {
                // set button icon
                icon = AppCompatResources.getDrawable(
                    this@MainActivity,
                    R.drawable.ic_round_pause_24
                )
                // set button text
                text = getText(R.string.pause)
            }
        } else { // show play button if false
            playPauseButton.apply {
                // set button icon
                icon = AppCompatResources.getDrawable(
                    this@MainActivity,
                    R.drawable.ic_round_play_arrow_24
                )
                // set button text
                text = getString(R.string.play)
            }
        }

        // get progress of tour every second
        lifecycleScope.launch {
            // run as long as KML tour status is "Playing"
            while (kmlTourStatus == "Playing") {
                // get percentage of current position over total duration
                val tourProgressInt = ((kmlTourController.currentPosition.value * 100.0)
                        / (kmlTourController.totalDuration.value)).roundToInt()
                tourProgressBar.progress = tourProgressInt
                // set a second delay
                delay(1000)
            }
        }

    }

    private fun showError(message: String) {
        Log.e(localClassName, message)
        Snackbar.make(sceneView, 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.