Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

[New] List contents of KML file #526

Merged
merged 10 commits into from
Oct 23, 2024
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
27 changes: 27 additions & 0 deletions Samples.xcodeproj/project.pbxproj
Original file line number Diff line number Diff line change
Expand Up @@ -341,6 +341,9 @@
D75B58512AAFB3030038B3B4 /* StyleFeaturesWithCustomDictionaryView.swift in Sources */ = {isa = PBXBuildFile; fileRef = D75B58502AAFB3030038B3B4 /* StyleFeaturesWithCustomDictionaryView.swift */; };
D75B58522AAFB37C0038B3B4 /* StyleFeaturesWithCustomDictionaryView.swift in Copy Source Code Files */ = {isa = PBXBuildFile; fileRef = D75B58502AAFB3030038B3B4 /* StyleFeaturesWithCustomDictionaryView.swift */; };
D75C35672AB50338003CD55F /* GroupLayersTogetherView.GroupLayerListView.swift in Sources */ = {isa = PBXBuildFile; fileRef = D75C35662AB50338003CD55F /* GroupLayersTogetherView.GroupLayerListView.swift */; };
D75E5EE62CC0340100252595 /* ListContentsOfKMLFileView.swift in Sources */ = {isa = PBXBuildFile; fileRef = D75E5EE22CC0340100252595 /* ListContentsOfKMLFileView.swift */; };
D75E5EE92CC0342700252595 /* ListContentsOfKMLFileView.swift in Copy Source Code Files */ = {isa = PBXBuildFile; fileRef = D75E5EE22CC0340100252595 /* ListContentsOfKMLFileView.swift */; };
D75E5EEC2CC0466900252595 /* esri_test_data.kmz in Resources */ = {isa = PBXBuildFile; fileRef = D75E5EEA2CC0466900252595 /* esri_test_data.kmz */; settings = {ASSET_TAGS = (ListContentsOfKmlFile, ); }; };
D75F66362B48EABC00434974 /* SearchForWebMapView.swift in Sources */ = {isa = PBXBuildFile; fileRef = D75F66332B48EABC00434974 /* SearchForWebMapView.swift */; };
D75F66392B48EB1800434974 /* SearchForWebMapView.swift in Copy Source Code Files */ = {isa = PBXBuildFile; fileRef = D75F66332B48EABC00434974 /* SearchForWebMapView.swift */; };
D76000A22AF18BAB00B3084D /* FindRouteInTransportNetworkView.Model.swift in Copy Source Code Files */ = {isa = PBXBuildFile; fileRef = D7749AD52AF08BF50086632F /* FindRouteInTransportNetworkView.Model.swift */; };
Expand Down Expand Up @@ -564,6 +567,7 @@
dstPath = "";
dstSubfolderSpec = 7;
files = (
D75E5EE92CC0342700252595 /* ListContentsOfKMLFileView.swift in Copy Source Code Files */,
D7201CDB2CC6B72A004BDB7D /* AddTiledLayerAsBasemapView.swift in Copy Source Code Files */,
D7BE7E722CC19CE5006DDB0C /* AddTiledLayerView.swift in Copy Source Code Files */,
D7BEBAD52CBDFE3900F882E7 /* DisplayAlternateSymbolsAtDifferentScalesView.swift in Copy Source Code Files */,
Expand Down Expand Up @@ -973,6 +977,8 @@
D7588F5C2B7D8DAA008B75E2 /* NavigateRouteWithReroutingView.swift */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.swift; path = NavigateRouteWithReroutingView.swift; sourceTree = "<group>"; };
D75B58502AAFB3030038B3B4 /* StyleFeaturesWithCustomDictionaryView.swift */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.swift; path = StyleFeaturesWithCustomDictionaryView.swift; sourceTree = "<group>"; };
D75C35662AB50338003CD55F /* GroupLayersTogetherView.GroupLayerListView.swift */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.swift; path = GroupLayersTogetherView.GroupLayerListView.swift; sourceTree = "<group>"; };
D75E5EE22CC0340100252595 /* ListContentsOfKMLFileView.swift */ = {isa = PBXFileReference; lastKnownFileType = sourcecode.swift; path = ListContentsOfKMLFileView.swift; sourceTree = "<group>"; };
D75E5EEA2CC0466900252595 /* esri_test_data.kmz */ = {isa = PBXFileReference; lastKnownFileType = file; path = esri_test_data.kmz; sourceTree = "<group>"; };
D75F66332B48EABC00434974 /* SearchForWebMapView.swift */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.swift; path = SearchForWebMapView.swift; sourceTree = "<group>"; };
D76000AB2AF19C2300B3084D /* FindRouteInMobileMapPackageView.swift */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.swift; path = FindRouteInMobileMapPackageView.swift; sourceTree = "<group>"; };
D76000B62AF19FCA00B3084D /* SanFrancisco.mmpk */ = {isa = PBXFileReference; lastKnownFileType = file; path = SanFrancisco.mmpk; sourceTree = "<group>"; };
Expand Down Expand Up @@ -1290,6 +1296,7 @@
D70082E72ACF8F6C00E0C3C2 /* Identify KML features */,
D751018A2A2E960300B8FA48 /* Identify layer features */,
D7464F182ACE0445007FEE88 /* Identify raster cell */,
D75E5EE52CC0340100252595 /* List contents of KML file */,
D776880E2B69826B007C3860 /* List spatial reference transformations */,
D718A1E92B575FD900447087 /* Manage bookmarks */,
D752D93C2A3914E5003EB25E /* Manage operational layers */,
Expand Down Expand Up @@ -1479,6 +1486,7 @@
00D4EF8128638BF100B9CC30 /* cb1b20748a9f4d128dad8a87244e3e37 */,
4D126D7629CA3B3F00CFB7A7 /* d5bad9f4fee9483791e405880fb466da */,
D77572AC2A295DC100F490CD /* d1453556d91e46dea191c20c398b82cd */,
D75E5EEB2CC0466900252595 /* da301cb122874d5497f8a8f6c81eb36e */,
D7E7D0862AEB3C36003AAD02 /* df193653ed39449195af0c9725701dca */,
F111CCC2288B63DB00205358 /* e1f3a7254cb845b09450f54937c16061 */,
D7C5233F2BED9BBF00E8221A /* e4a398afe9a945f3b0f4dca1e4faccb5 */,
Expand Down Expand Up @@ -2346,6 +2354,22 @@
path = "Style features with custom dictionary";
sourceTree = "<group>";
};
D75E5EE52CC0340100252595 /* List contents of KML file */ = {
isa = PBXGroup;
children = (
D75E5EE22CC0340100252595 /* ListContentsOfKMLFileView.swift */,
);
path = "List contents of KML file";
sourceTree = "<group>";
};
D75E5EEB2CC0466900252595 /* da301cb122874d5497f8a8f6c81eb36e */ = {
isa = PBXGroup;
children = (
D75E5EEA2CC0466900252595 /* esri_test_data.kmz */,
);
path = da301cb122874d5497f8a8f6c81eb36e;
sourceTree = "<group>";
};
D75F66322B48EABC00434974 /* Search for web map */ = {
isa = PBXGroup;
children = (
Expand Down Expand Up @@ -3107,6 +3131,7 @@
GenerateOfflineMapWithLocalBasemap,
GeocodeOffline,
IdentifyRasterCell,
ListContentsOfKmlFile,
NavigateRouteWithRerouting,
OrbitCameraAroundObject,
ShowDeviceLocationWithNmeaDataSources,
Expand Down Expand Up @@ -3189,6 +3214,7 @@
D7E7D09A2AEB3C47003AAD02 /* san_diego_offline_routing in Resources */,
F111CCC4288B641900205358 /* Yellowstone.mmpk in Resources */,
D77572AE2A295DDE00F490CD /* PacificSouthWest2 in Resources */,
D75E5EEC2CC0466900252595 /* esri_test_data.kmz in Resources */,
10D321932BDB187400B39B1B /* naperville_imagery.tpkx in Resources */,
00D4EFB12863CE6300B9CC30 /* ScottishWildlifeTrust_reserves in Resources */,
D7781D492B7EB03400E53C51 /* SanDiegoTourPath.json in Resources */,
Expand Down Expand Up @@ -3399,6 +3425,7 @@
1C19B4F12A578E46001D2506 /* CreateLoadReportView.Views.swift in Sources */,
E066DD3B2860CA08004D3D5B /* ShowResultOfSpatialRelationshipsView.swift in Sources */,
7573E81E29D6134C00BEED9C /* TraceUtilityNetworkView.Views.swift in Sources */,
D75E5EE62CC0340100252595 /* ListContentsOfKMLFileView.swift in Sources */,
4D2ADC5A29C4F612003B367F /* ChangeMapViewBackgroundView.swift in Sources */,
95DEB9B62C127A92009BEC35 /* ShowViewshedFromPointOnMapView.swift in Sources */,
D7BA38972BFBFC0F009954F5 /* QueryRelatedFeaturesView.swift in Sources */,
Expand Down
Original file line number Diff line number Diff line change
@@ -0,0 +1,261 @@
// Copyright 2024 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
//
// https://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 ArcGIS
import SwiftUI

struct ListContentsOfKMLFileView: View {
/// The view model for the sample.
@StateObject private var model = Model()

var body: some View {
VStack(spacing: 0) {
Text("Tap on a disclosure to reveal a node's children. Tap on a node to open it in a scene.")
.multilineTextAlignment(.center)
.frame(maxWidth: .infinity, alignment: .center)
.padding(8)
.background(Color(.systemGroupedBackground))

// Recursively displays the dataset's nodes in a list.
List(model.kmlDataset?.rootNodes ?? [], id: \.name, children: \.children) { node in
VStack(alignment: .leading) {
NavigationLink {
if let viewpoint = model.nodeViewpoints[node.name] {
SceneView(scene: model.scene, viewpoint: viewpoint)
.navigationTitle(node.name)
} else {
Text("This node has no extent to view.")
.navigationTitle(node.name)
}
} label: {
VStack(alignment: .leading) {
if !node.name.isEmpty {
Text(node.name)
}
Text(node.typeLabel)
.font(.footnote)
}
#if targetEnvironment(macCatalyst)
.padding(.leading)
#endif
}
}
}
}
.errorAlert(presentingError: $model.error)
}
}

// MARK: Model

private extension ListContentsOfKMLFileView {
/// The view model for the sample.
@MainActor
final class Model: ObservableObject {
/// A dataset containing the KML data from a local file.
@Published private(set) var kmlDataset: KMLDataset?

/// The viewpoints for the nodes in the dataset.
@Published private(set) var nodeViewpoints: [String: Viewpoint] = [:]

/// The error shown in the error alert.
@Published var error: Error?

/// A scene for displaying the KML data.
let scene: ArcGIS.Scene = {
let scene = Scene(basemapStyle: .arcGISImagery)
let elevationSource = ArcGISTiledElevationSource(url: .worldElevationService)
scene.baseSurface.addElevationSource(elevationSource)
return scene
}()

/// The task used for the asynchronous setup operations.
private var setupTask: Task<Void, Never>?

init() {
setupTask = Task { [weak self] in
CalebRas marked this conversation as resolved.
Show resolved Hide resolved
guard let self else { return }

do {
try await setUpKMLDataset()
} catch {
self.error = error
}
}
}

deinit {
setupTask?.cancel()
}

/// Sets up the KML dataset and adds it to the scene as layer.
private func setUpKMLDataset() async throws {
// Creates the dataset using a local ".kml" file in the bundle.
let kmlDataset = KMLDataset(name: "esri_test_data", bundle: .main)!
try await kmlDataset.load()
self.kmlDataset = kmlDataset

// Adds the dataset to the scene as a KML layer.
let kmlLayer = KMLLayer(dataset: kmlDataset)
scene.addOperationalLayer(kmlLayer)
try await scene.load()

try await setUpKMLNodes(kmlDataset.rootNodes)
}

/// Recursively creates viewpoints for KML nodes in a given list.
/// - Parameter kmlNodes: The list of KML nodes to set up.
private func setUpKMLNodes(_ kmlNodes: [KMLNode]) async throws {
// Loads the surface so that the elevation can be queried when the viewpoint is made.
try await scene.baseSurface.load()

for node in kmlNodes {
let viewpoint = try await Viewpoint(kmlNode: node, surface: scene.baseSurface)
nodeViewpoints[node.name] = viewpoint

// Ensures the node is visible since some are hidden by default.
node.isVisible = true

if let childNodes = node.children {
try await setUpKMLNodes(childNodes)
}
}
}
}
}

// MARK: Helper Extensions

private extension KMLNode {
/// The child nodes of the node, if any.
var children: [KMLNode]? {
CalebRas marked this conversation as resolved.
Show resolved Hide resolved
switch self {
case let container as KMLContainer:
container.childNodes
case let networkLink as KMLNetworkLink:
networkLink.childNodes
default:
nil
}
}

/// A human-readable label of the type of the node.
var typeLabel: String {
switch self {
case is KMLDocument: "Document"
case is KMLFolder: "Folder"
case is KMLContainer: "Container"
case is KMLGroundOverlay: "Ground Overlay"
case is KMLNetworkLink: "Network Link"
case is KMLPhotoOverlay: "Photo Overlay"
case is KMLPlacemark: "Placemark"
case is KMLScreenOverlay: "Screen Overlay"
case is KMLTour: "Tour"
default: "Unknown"
}
}
}

private extension Viewpoint {
/// Creates a viewpoint from a KML node.
/// - Parameters:
/// - kmlNode: The KML node.
/// - surface: A surface that determines the elevation needed to offset the viewpoint.
init?(kmlNode: KMLNode, surface: Surface) async throws {
if let kmlViewpoint = kmlNode.viewpoint {
try await self.init(kmlViewpoint: kmlViewpoint, surface: surface)
} else if let extent = kmlNode.extent {
// Creates a viewpoint with node's extent if it doesn't have a predefined viewpoint.
try await self.init(kmlNodeExtent: extent, surface: surface)
} else {
return nil
}
}

/// Creates a viewpoint from a KML viewpoint.
/// - Parameters:
/// - kmlViewpoint: The KML viewpoint.
/// - surface: A surface that determines the elevation needed to offset the viewpoint.
private init(kmlViewpoint: KMLViewpoint, surface: Surface) async throws {
switch kmlViewpoint.kind {
case .lookAt:
var lookAtPoint = kmlViewpoint.location
if kmlViewpoint.altitudeMode != .absolute {
// If the elevation is relative, account for the surface's elevation.
let elevation = try await surface.elevation(at: kmlViewpoint.location)
lookAtPoint = kmlViewpoint.location.withBuilder { $0.z += elevation }
}

let camera = Camera(
lookingAt: lookAtPoint,
distance: kmlViewpoint.range,
heading: kmlViewpoint.heading,
pitch: kmlViewpoint.pitch,
roll: kmlViewpoint.roll
)
self.init(latitude: .nan, longitude: .nan, scale: .nan, camera: camera)
case .camera:
let camera = Camera(
location: kmlViewpoint.location,
heading: kmlViewpoint.heading,
pitch: kmlViewpoint.pitch,
roll: kmlViewpoint.roll
)
self.init(latitude: .nan, longitude: .nan, scale: .nan, camera: camera)
@unknown default:
fatalError("Unexpected KMLViewpoint.Kind: \(kmlViewpoint.kind)")
}
}

/// Creates a viewpoint from the extent of a KML node.
/// - Parameters:
/// - extent: The extent of a KML node.
/// - surface: A surface that determines the elevation needed to offset the viewpoint.
private init?(kmlNodeExtent extent: Envelope, surface: Surface) async throws {
// Ensures the extent isn't empty since some nodes don't include a geometry.
guard !extent.isEmpty else { return nil }

let extentCenter = extent.center
let elevation = try await surface.elevation(at: extentCenter)

if extent.extent.width == 0, extent.height == 0 {
// If the extent is not empty, but the width and height are still zero,
// default values (based on Google Earth) are used to create a camera.
let elevatedCenter = extentCenter.withBuilder { $0.z += elevation }
let camera = Camera(
lookingAt: elevatedCenter,
distance: 1000,
heading: 0,
pitch: 45,
roll: 0
)
self.init(latitude: .nan, longitude: .nan, scale: .nan, camera: camera)
} else {
// Adds the elevation and a buffer to the extent.
let bufferedExtent = extent.withBuilder { builder in
builder.zMin += elevation
builder.zMax += elevation
builder.expand(by: 1.1)
}
self.init(boundingGeometry: bufferedExtent)
}
}
}

private extension URL {
/// A web URL to the Terrain3D image server on ArcGIS REST.
static var worldElevationService: URL {
URL(string: "https://elevation3d.arcgis.com/arcgis/rest/services/WorldElevation3D/Terrain3D/ImageServer")!
}
}
41 changes: 41 additions & 0 deletions Shared/Samples/List contents of KML file/README.md
Original file line number Diff line number Diff line change
@@ -0,0 +1,41 @@
# List contents of KML file

List the contents of a KML file.

![Screenshot of List contents of KML file sample](list-contents-of-kml-file.png)

## 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. Tap on a disclosure to reveal a node's children. Tap on a node to open it in a scene zoomed to that node. Not all nodes can be zoomed to (e.g., screen overlays).

## How it works

1. Add the KML file to the scene as a layer.
2. Explore the root nodes of the `KMLDataset` 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.
3. When a node is selected, use the node's `extent` to create a `Viewpoint` and pass it to the `SceneView`.

## Relevant API

* KMLContainer
* KMLDataset
* KMLDocument
* KMLFolder
* KMLGroundOverlay
* KMLLayer
* KMLNetworkLink
* KMLNode
* KMLPlacemark
* KMLScreenOverlay

## Offline data

This sample uses the [esri_test_data](https://www.arcgis.com/home/item.html?id=da301cb122874d5497f8a8f6c81eb36e) KML file. It is downloaded from ArcGIS Online automatically.

## Tags

Keyhole, KML, KMZ, layers, OGC
Loading
Loading