Identify KML features

View inAndroidFormsUWPWPFWinUIiOSView on GitHub

Show a callout with formatted content for a KML feature.

Image of identify KML features

Use case

A user may wish to select a KML feature to view relevant information about it.

How to use the sample

Tap a feature to identify it. Feature information will be displayed in a callout.

Note: the KML layer used in this sample contains a screen overlay. The screen overlay contains a legend and the logos for NOAA and the NWS. You can't identify the screen overlay.

How it works

  1. Create a listener for the GeoViewTapped event of the MapView.
  2. On tap:
  • Dismiss the Callout, if one is showing.
  • Call IdentifyLayersAsync(...) passing in the KmlLayer, screen point and tolerance.
  • Await the result of the identify and then get the KmlPlacemark from the result.
  • Create a callout at the calculated map point and populate the callout content with text from the placemark's BalloonContent. NOTE: KML supports defining HTML for balloon content and may need to be converted from HTML to text.
  • Show the callout.

Note: There are several types of KML features. This sample only identifies features of type KmlPlacemark.

Relevant API

  • GeoView.IdentifyLayerAsync
  • IdentifyLayerResult
  • KmlLayer
  • KmlPlacemark
  • KmlPlacemark.BalloonContent

About the data

This sample shows a forecast for significant weather within the U.S. Regions of severe thunderstorms, flooding, snowfall, and freezing rain are shown. Tap the features to see details.

Additional information

KML features can have rich HTML content, including images.

Tags

Keyhole, KML, KMZ, NOAA, NWS, OGC, weather

Sample Code

IdentifyKmlFeatures.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
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
// 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.

using System;
using System.Linq;
using ArcGISRuntime;
using CoreGraphics;
using Esri.ArcGISRuntime.Data;
using Esri.ArcGISRuntime.Geometry;
using Esri.ArcGISRuntime.Mapping;
using Esri.ArcGISRuntime.Ogc;
using Esri.ArcGISRuntime.UI.Controls;
using Foundation;
using UIKit;
using WebKit;

namespace ArcGISRuntimeXamarin.Samples.IdentifyKmlFeatures
{
    [Register("IdentifyKmlFeatures")]
    [ArcGISRuntime.Samples.Shared.Attributes.Sample(
        name: "Identify KML features",
        category: "Layers",
        description: "Show a callout with formatted content for a KML feature.",
        instructions: "Tap a feature to identify it. Feature information will be displayed in a callout.",
        tags: new[] { "KML", "KMZ", "Keyhole", "NOAA", "NWS", "OGC", "weather" })]
    public class IdentifyKmlFeatures : UIViewController
    {
        // Hold references to UI controls.
        private MapView _myMapView;
        private WKWebView _webView;
        private UIStackView _stackView;

        // Hold a reference to the KML layer for use in identify operations.
        private KmlLayer _forecastLayer;

        // Initial view envelope.
        private readonly Envelope _usEnvelope = new Envelope(-144.619561355187, 18.0328662832097, -66.0903762761083, 67.6390975806745, SpatialReferences.Wgs84);

        public IdentifyKmlFeatures()
        {
            Title = "Identify KML features";
        }

        private void Initialize()
        {
            // Set up the basemap.
            _myMapView.Map = new Map(BasemapStyle.ArcGISDarkGray);

            // Create the dataset.
            KmlDataset dataset = new KmlDataset(new Uri("https://www.wpc.ncep.noaa.gov/kml/noaa_chart/WPC_Day1_SigWx_latest.kml"));

            // Create the layer from the dataset.
            _forecastLayer = new KmlLayer(dataset);

            // Add the layer to the map.
            _myMapView.Map.OperationalLayers.Add(_forecastLayer);

            // Zoom to the extent of the United States.
            _myMapView.SetViewpoint(new Viewpoint(_usEnvelope));
        }

        private async void MyMapView_GeoViewTapped(object sender, GeoViewInputEventArgs e)
        {
            // Clear any existing popups.
            _myMapView.DismissCallout();

            try
            {
                // Perform identify on the KML layer and get the results.
                IdentifyLayerResult identifyResult = await _myMapView.IdentifyLayerAsync(_forecastLayer, e.Position, 2, false);

                // Return if there are no results that are KML placemarks.
                if (!identifyResult.GeoElements.OfType<KmlGeoElement>().Any())
                {
                    return;
                }

                // Get the first identified feature that is a KML placemark
                KmlNode firstIdentifiedPlacemark = identifyResult.GeoElements.OfType<KmlGeoElement>().First().KmlNode;

                if (string.IsNullOrEmpty(firstIdentifiedPlacemark.Description))
                {
                    firstIdentifiedPlacemark.Description = "Weather condition";
                }

                // Show a preview with the HTML content.
                _webView.LoadHtmlString(new NSString(firstIdentifiedPlacemark.BalloonContent), new NSUrl(""));
            }
            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 };

            _webView = new WKWebView(new CGRect(), new WKWebViewConfiguration());
            _myMapView = new MapView();

            _stackView = new UIStackView(new UIView[] {_myMapView, _webView})
            {
                Alignment = UIStackViewAlignment.Fill,
                Distribution = UIStackViewDistribution.FillEqually,
                TranslatesAutoresizingMaskIntoConstraints = false
            };

            // Add the views.
            View.AddSubview(_stackView);

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

            SetLayoutOrientation();
        }

        public override void TraitCollectionDidChange(UITraitCollection previousTraitCollection)
        {
            base.TraitCollectionDidChange(previousTraitCollection);
            SetLayoutOrientation();
        }

        private void SetLayoutOrientation()
        {
            if (View.TraitCollection.VerticalSizeClass == UIUserInterfaceSizeClass.Compact)
            {
                // Landscape
                _stackView.Axis = UILayoutConstraintAxis.Horizontal;
            }
            else
            {
                // Portrait
                _stackView.Axis = UILayoutConstraintAxis.Vertical;
            }
        }

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

            // Subscribe to events.
            _myMapView.GeoViewTapped += MyMapView_GeoViewTapped;
        }

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

            // Unsubscribe from events, per best practice.
            _myMapView.GeoViewTapped -= MyMapView_GeoViewTapped;
        }
    }
}

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