Display KML

View inAndroidFormsUWPWPFWinUIiOSView on GitHub

Display KML from a URL, portal item, or local KML file.

Image of display KML

Use case

Keyhole Markup Language (KML) is a data format used by Google Earth. KML is popular as a transmission format for consumer use and for sharing geographic data between apps. You can use Runtime to display KML files, with full support for a variety of features, including network links, 3D models, screen overlays, and tours.

How to use the sample

Use the UI to select a source. A KML file from that source will be loaded and displayed in the scene.

How it works

  1. To create a KML layer from a URL, create a KmlDataset using the URL to the KML file. Then pass the dataset to the KmlLayer constructor.
  2. To create a KML layer from a portal item, construct a PortalItem with a Portal and the KML portal item ID. Pass the portal item to the KmlLayer constructor.
  3. To create a KML layer from a local file, create a KmlDataset using the absolute file path to the local KML file. Then pass the dataset to the KmlLayer constructor.
  4. Add the layer as an operational layer to the scene with scene.OperationalLayers.Add(kmlLayer).

Relevant API

  • KmlDataset
  • KmlLayer

Offline data

This sample uses US state capitals KML file. It is downloaded from ArcGIS Online automatically.

About the data

This sample displays three different KML files:

  • From URL - this is a map of the significant weather outlook produced by NOAA/NWS. It uses KML network links to always show the latest data.
  • From local file - this is a map of U.S. state capitals. It doesn't define an icon, so the default pushpin is used for the points.
  • From portal item - this is a map of U.S. states.

Tags

keyhole, KML, KMZ, OGC

Sample Code

DisplayKml.cs
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
// 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.

using System;
using ArcGISRuntime;
using ArcGISRuntime.Samples.Managers;
using Esri.ArcGISRuntime.Geometry;
using Esri.ArcGISRuntime.Mapping;
using Esri.ArcGISRuntime.Portal;
using Esri.ArcGISRuntime.UI.Controls;
using Foundation;
using UIKit;

namespace ArcGISRuntimeXamarin.Samples.DisplayKml
{
    [Register("DisplayKml")]
    [ArcGISRuntime.Samples.Shared.Attributes.Sample(
        name: "Display KML",
        category: "Layers",
        description: "Display KML from a URL, portal item, or local KML file.",
        instructions: "Use the UI to select a source. A KML file from that source will be loaded and displayed in the scene.",
        tags: new[] { "KML", "KMZ", "OGC", "keyhole" })]
    [ArcGISRuntime.Samples.Shared.Attributes.OfflineData("324e4742820e46cfbe5029ff2c32cb1f")]
    public class DisplayKml : UIViewController
    {
        // Hold references to UI controls.
        private SceneView _mySceneView;
        private UISegmentedControl _dataChoiceButton;

        private readonly Envelope _usEnvelope = new Envelope(-144.619561355187, 18.0328662832097, -66.0903762761083, 67.6390975806745, SpatialReferences.Wgs84);
        private readonly string[] _sources = {"URL", "Local file", "Portal item"};

        public DisplayKml()
        {
            Title = "Display KML";
        }

        private void Initialize()
        {
            // Set up the basemap.
            _mySceneView.Scene = new Scene(BasemapStyle.ArcGISImagery);
        }

        private async void DataChoiceButtonOnValueChanged(object sender, EventArgs e)
        {
            // Clear existing layers.
            _mySceneView.Scene.OperationalLayers.Clear();

            // Get the name of the selected layer.
            string name = _sources[((UISegmentedControl) sender).SelectedSegment];

            try
            {
                // Create the layer using the chosen constructor.
                KmlLayer layer;
                switch (name)
                {
                    case "URL":
                    default:
                        layer = new KmlLayer(new Uri("https://www.wpc.ncep.noaa.gov/kml/noaa_chart/WPC_Day1_SigWx.kml"));
                        break;
                    case "Local file":
                        string filePath = DataManager.GetDataFolder("324e4742820e46cfbe5029ff2c32cb1f", "US_State_Capitals.kml");
                        layer = new KmlLayer(new Uri(filePath));
                        break;
                    case "Portal item":
                        ArcGISPortal portal = await ArcGISPortal.CreateAsync();
                        PortalItem item = await PortalItem.CreateAsync(portal, "9fe0b1bfdcd64c83bd77ea0452c76253");
                        layer = new KmlLayer(item);
                        break;
                }

                // Add the selected layer to the map.
                _mySceneView.Scene.OperationalLayers.Add(layer);

                // Zoom to the extent of the United States.
                await _mySceneView.SetViewpointAsync(new Viewpoint(_usEnvelope));
            }
            catch (Exception ex)
            {
                new UIAlertView("Error", ex.ToString(), (IUIAlertViewDelegate) null, "OK", null).Show();
            }
        }

        public override void ViewDidLoad()
        {
            base.ViewDidLoad();
            Initialize();
        }

        public override void LoadView()
        {
            // Create the views.
            View = new UIView() { BackgroundColor = ApplicationTheme.BackgroundColor };

            _mySceneView = new SceneView();
            _mySceneView.TranslatesAutoresizingMaskIntoConstraints = false;

            _dataChoiceButton = new UISegmentedControl(_sources)
            {
                BackgroundColor = ApplicationTheme.BackgroundColor,
                TranslatesAutoresizingMaskIntoConstraints = false
            };

            // Clean up borders of segmented control - avoid corner pixels.
            _dataChoiceButton.ClipsToBounds = true;
            _dataChoiceButton.Layer.CornerRadius = 5;

            // Add the views.
            View.AddSubviews(_mySceneView, _dataChoiceButton);

            // Lay out the views.
            NSLayoutConstraint.ActivateConstraints(new[]
            {
                _mySceneView.TopAnchor.ConstraintEqualTo(View.SafeAreaLayoutGuide.TopAnchor),
                _mySceneView.LeadingAnchor.ConstraintEqualTo(View.LeadingAnchor),
                _mySceneView.TrailingAnchor.ConstraintEqualTo(View.TrailingAnchor),
                _mySceneView.BottomAnchor.ConstraintEqualTo(View.BottomAnchor),

                _dataChoiceButton.LeadingAnchor.ConstraintEqualTo(View.LayoutMarginsGuide.LeadingAnchor),
                _dataChoiceButton.TrailingAnchor.ConstraintEqualTo(View.LayoutMarginsGuide.TrailingAnchor),
                _dataChoiceButton.TopAnchor.ConstraintEqualTo(View.SafeAreaLayoutGuide.TopAnchor, 8)
            });
        }

        public override void ViewWillAppear(bool animated)
        {
            base.ViewWillAppear(animated);

            // Subscribe to events.
            _dataChoiceButton.ValueChanged += DataChoiceButtonOnValueChanged;
        }

        public override void ViewDidDisappear(bool animated)
        {
            base.ViewDidDisappear(animated);

            // Unsubscribe from events, per best practice.
            _dataChoiceButton.ValueChanged -= DataChoiceButtonOnValueChanged;
        }
    }
}

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