List KML contents

View on GitHubSample viewer app

List the contents of a KML file.

List KML contents

Use case

KML files can contain a hierarchy of features, including network links to other KML content. A user may wish to traverse through the contents of KML nodes to know what data is contained within each node and, recursively, their children.

How to use the sample

The contents of the KML file are shown in a tree. Select a node to zoom to that node. Not all nodes can be zoomed to (e.g. screen overlays).

How it works

  1. Apply an AGSKMLDataset to the AGSSceneView's kmlDatasaet.
  2. Explore the root nodes of the AGSKMLDataset recursively explored to create a view model.
  • Each node is enabled for display at this step. KML files may include nodes that are turned off by default.
  1. When a node is selected, use the node's extent to determine an AGSViewpoint and set it to the AGSSceneView.

Relevant API

  • AGSKMLContainer
  • AGSKMLDataset
  • AGSKMLDocument
  • AGSKMLFolder
  • AGSKMLGroundOverlay
  • AGSKMLLayer
  • AGSKMLNetworkLink
  • AGSKMLNode
  • AGSKMLPlacemark
  • AGSKMLScreenOverlay

Tags

Keyhole, KML, KMZ, layers, OGC

Sample Code

ListKMLContentsSceneViewController.swiftListKMLContentsSceneViewController.swiftListKMLContentsViewController.swift
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
// Copyright 2018 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.

import UIKit
import ArcGIS

class ListKMLContentsSceneViewController: UIViewController {
    @IBOutlet weak var sceneView: AGSSceneView? {
        didSet {
            sceneView?.scene = scene
        }
    }

    private let scene: AGSScene = {
        // initialize scene with labeled imagery
        let scene = AGSScene(basemapStyle: .arcGISImagery)

        // create an elevation source and add it to the scene's surface
        let elevationSourceURL = URL(string: "https://elevation3d.arcgis.com/arcgis/rest/services/WorldElevation3D/Terrain3D/ImageServer")!
        let elevationSource = AGSArcGISTiledElevationSource(url: elevationSourceURL)
        scene.baseSurface?.elevationSources.append(elevationSource)

        return scene
    }()

    var kmlDataset: AGSKMLDataset? {
        didSet {
            guard kmlDataset != oldValue,
                let kmlDataset = kmlDataset else {
                    return
            }

            // clear any existing layers
            scene.operationalLayers.removeAllObjects()

            // create a layer to display the dataset
            let kmlLayer = AGSKMLLayer(kmlDataset: kmlDataset)
            // add the kml layer to the scene
            scene.operationalLayers.add(kmlLayer)
        }
    }
    var node: AGSKMLNode? {
        didSet {
            guard kmlDataset != oldValue,
                let node = node else {
                return
            }
            // set the title so the name will appear in the navigation bar
            title = node.name

            // set the viewpoint based on the new node
            setSceneViewpoint(for: node)
        }
    }

    /// A queue for calculating the node viewpoint in the background.
    private let dispatchQueue = DispatchQueue(label: "node viewpoint getter", qos: .userInitiated, attributes: .concurrent, autoreleaseFrequency: .workItem, target: nil)

    // MARK: - Viewpoint

    /// Sets the viewpoint of the scene based on the node, or hides the node
    /// if a viewpoint cannot be determined.
    private func setSceneViewpoint(for node: AGSKMLNode) {
        dispatchQueue.async {
            // get the viewpoint asynchronously so not to block the main thread
            let nodeViewpoint = self.viewpoint(for: node)

            // run UI updates on the main thread
            DispatchQueue.main.async {
                // load the view before setting a viewpoint
                self.loadViewIfNeeded()

                guard let sceneView = self.sceneView else {
                    return
                }

                if let nodeViewpoint = nodeViewpoint,
                    !nodeViewpoint.targetGeometry.isEmpty {
                    // reveal the view in case it was previously hidden
                    sceneView.isHidden = false

                    // set the viewpoint for the node
                    sceneView.setViewpoint(nodeViewpoint)
                } else {
                    // this node has no viewpoint so hide the scene view, showing the info text
                    sceneView.isHidden = true
                }
            }
        }
    }

    /// Returns the elevation of the scene's surface corresponding to the point's x/y.
    private func sceneSurfaceElevation(for point: AGSPoint) -> Double? {
        guard let surface = scene.baseSurface else {
            return nil
        }

        var surfaceElevation: Double?
        let group = DispatchGroup()
        group.enter()
        // we want to return the elevation synchronously, so run the task in the background and wait
        surface.elevation(for: point) { (elevation, error) in
            if error == nil {
                surfaceElevation = elevation
            }
            group.leave()
        }
        // wait, but not longer than three seconds
        _ = group.wait(timeout: .now() + 3)
        return surfaceElevation
    }

    /// Returns the viewpoint showing the node, converting it from the node's AGSKMLViewPoint if possible.
    private func viewpoint(for node: AGSKMLNode) -> AGSViewpoint? {
        if let kmlViewpoint = node.viewpoint {
            return viewpointFromKMLViewpoint(kmlViewpoint)
        } else if let extent = node.extent {
            // the node does not have a predefined viewpoint, so create a viewpoint based on its extent
            return viewpointFromKMLNodeExtent(extent)
        }
        // the node doesn't have a predefined viewpoint or geometry
        return nil
    }

    // Converts the KML viewpoint to a viewpoint for the scene.
    // The KML viewpoint may not correspond to the node's geometry.
    private func viewpointFromKMLViewpoint(_ kmlViewpoint: AGSKMLViewpoint) -> AGSViewpoint? {
        switch kmlViewpoint.type {
        case .lookAt:
            var lookAtPoint = kmlViewpoint.location
            if kmlViewpoint.altitudeMode != .absolute {
                // if the elevation is relative, account for the surface's elevation
                let elevation = sceneSurfaceElevation(for: lookAtPoint) ?? 0
                lookAtPoint = AGSPoint(x: lookAtPoint.x, y: lookAtPoint.y, z: lookAtPoint.z + elevation, spatialReference: lookAtPoint.spatialReference)
            }
            let camera = AGSCamera(lookAt: lookAtPoint,
                                   distance: kmlViewpoint.range,
                                   heading: kmlViewpoint.heading,
                                   pitch: kmlViewpoint.pitch,
                                   roll: kmlViewpoint.roll)
            // only the camera parameter is used by the scene
            return AGSViewpoint(center: kmlViewpoint.location, scale: 1, camera: camera)
        case .camera:
            // convert the KML viewpoint to a camera
            let camera = AGSCamera(location: kmlViewpoint.location,
                                   heading: kmlViewpoint.heading,
                                   pitch: kmlViewpoint.pitch,
                                   roll: kmlViewpoint.roll)
            // only the camera parameter is used by the scene
            return AGSViewpoint(center: kmlViewpoint.location, scale: 1, camera: camera)
        case .unknown:
            fallthrough
        @unknown default:
            print("Unexpected AGSKMLViewpointType \(kmlViewpoint.type)")
            return nil
        }
    }

    /// Creates a default viewpoint framing the node based on its extent.
    private func viewpointFromKMLNodeExtent(_ extent: AGSEnvelope) -> AGSViewpoint? {
        // some nodes do not include a geometry, so check that the extent isn't empty
        guard !extent.isEmpty else {
            return nil
        }

        let extentCenter = extent.center
        // take the scene's elevation into account
        let elevation = sceneSurfaceElevation(for: extentCenter) ?? 0

        // It's possible for `isEmpty` to be false but for width/height to still be zero.
        if extent.width == 0,
            extent.height == 0 {
            let lookAtPoint = AGSPoint(
                x: extentCenter.x,
                y: extentCenter.y,
                z: extentCenter.z + elevation,
                spatialReference: extent.spatialReference
            )
            // Defaults based on Google Earth.
            let camera = AGSCamera(lookAt: lookAtPoint, distance: 1000, heading: 0, pitch: 45, roll: 0)
            // only the camera parameter is used by the scene
            return AGSViewpoint(targetExtent: extent, camera: camera)
        } else {
            // expand the extent to give some margins when framing the node
            let bufferRadius = max(extent.width, extent.height) / 20
            let bufferedExtent = AGSEnvelope(
                xMin: extent.xMin - bufferRadius,
                yMin: extent.yMin - bufferRadius,
                zMin: extent.zMin - bufferRadius + elevation,
                xMax: extent.xMax + bufferRadius,
                yMax: extent.yMax + bufferRadius,
                zMax: extent.zMax + bufferRadius + elevation,
                spatialReference: .wgs84()
            )
            return AGSViewpoint(targetExtent: bufferedExtent)
        }
    }
}

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