Create and save KML file

View inMAUIUWPWPFWinUIView on GitHubSample viewer app

Construct a KML document and save it as a KMZ file.

Image of create and save KML file

Use case

If you need to create and save data on the fly, you can use KML to create points, lines, and polygons by sketching on the map, customizing the style, and serializing them as KML nodes in a KML Document. Once complete, you can share the KML data with others that are using a KML reading application, such as ArcGIS Earth.

How to use the sample

Click on one of the buttons in the middle row to start adding a geometry. Click on the map view to place vertices. Click the "Complete Sketch" button to add the geometry to the KML document as a new KML placemark. Use the style interface to edit the style of the placemark. If you do not wish to set a style, click the "Don't Apply Style" button. When you are finished adding KML nodes, click on the "Save KMZ file" button to save the active KML document as a .kmz file on your system. Use the "Reset" button to clear the current KML document and start a new one.

How it works

  1. Create a KmlDocument
  2. Create a KmlDataset using the KmlDocument.
  3. Create a KmlLayer using the KmlDataset and add it to Map.OperationalLayers.
  4. Create Geometry using GeometryEditor.
  5. Project that Geometry to WGS84 using GeometryEngine.Project.
  6. Create a KmlGeometry object using that projected Geometry.
  7. Create a KmlPlacemark using the KmlGeometry.
  8. Add the KmlPlacemark to the KmlDocument.
  9. Set the KmlStyle for the KmlPlacemark.
  10. When finished with adding KmlPlacemark nodes to the KmlDocument, save the KmlDocument to a file using the SaveAsAsync method.

Relevant API

  • GeometryEditor
  • GeometryEngine.Project
  • KmlDataset
  • KmlDocument
  • KmlGeometry
  • KmlLayer
  • KmlNode.SaveAsASync
  • KmlPlacemark
  • KmlStyle

Tags

geometry editor, Keyhole, KML, KMZ, OGC

Sample Code

CreateAndSaveKmlFile.xaml.csCreateAndSaveKmlFile.xaml.csCreateAndSaveKmlFile.xaml
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
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
// Copyright 2019 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 Esri.ArcGISRuntime.Geometry;
using Esri.ArcGISRuntime.Mapping;
using Esri.ArcGISRuntime.Ogc;
using Esri.ArcGISRuntime.UI.Controls;
using Microsoft.Win32;
using System;
using System.Collections.Generic;
using System.Diagnostics;
using System.Drawing;
using System.Linq;
using System.Windows;
using System.Windows.Controls;
using Geometry = Esri.ArcGISRuntime.Geometry.Geometry;

namespace ArcGIS.WPF.Samples.CreateAndSaveKmlFile
{
    [ArcGIS.Samples.Shared.Attributes.Sample(
        name: "Create and save KML file",
        category: "Layers",
        description: "Construct a KML document and save it as a KMZ file.",
        instructions: "Click on one of the buttons in the middle row to start adding a geometry. Click on the map view to place vertices. Click the \"Complete Sketch\" button to add the geometry to the KML document as a new KML placemark. Use the style interface to edit the style of the placemark. If you do not wish to set a style, click the \"Don't Apply Style\" button. When you are finished adding KML nodes, click on the \"Save KMZ file\" button to save the active KML document as a .kmz file on your system. Use the \"Reset\" button to clear the current KML document and start a new one.",
        tags: new[] { "KML", "KMZ", "Keyhole", "OGC", "geometry editor" })]
    [ArcGIS.Samples.Shared.Attributes.OfflineData()]
    public partial class CreateAndSaveKmlFile
    {
        private KmlDocument _kmlDocument;
        private KmlDataset _kmlDataset;
        private KmlLayer _kmlLayer;
        private KmlPlacemark _currentPlacemark;
        private GeometryType _geometryType;

        public CreateAndSaveKmlFile()
        {
            InitializeComponent();
            Initialize();
        }

        private void Initialize()
        {
            // Create the map.
            MyMapView.Map = new Map(BasemapStyle.ArcGISImageryStandard);

            // Set the colors for the color picker.
            System.Reflection.PropertyInfo[] propertylist = typeof(Color).GetProperties(System.Reflection.BindingFlags.Static | System.Reflection.BindingFlags.Public);
            List<Color> colorList = propertylist.Select(x => (Color)x.GetValue(x)).ToList();
            colorList.RemoveAt(0);

            ColorPicker.ItemsSource = colorList;
            ColorPicker.SelectedIndex = 0;

            // Set the images for the point icon picker.
            List<string> iconLinks = new List<string>()
            {
                "https://static.arcgis.com/images/Symbols/Shapes/BlueCircleLargeB.png",
                "https://static.arcgis.com/images/Symbols/Shapes/BlueDiamondLargeB.png",
                "https://static.arcgis.com/images/Symbols/Shapes/BluePin1LargeB.png",
                "https://static.arcgis.com/images/Symbols/Shapes/BluePin2LargeB.png",
                "https://static.arcgis.com/images/Symbols/Shapes/BlueSquareLargeB.png",
                "https://static.arcgis.com/images/Symbols/Shapes/BlueStarLargeB.png"
            };
            List<Uri> iconList = iconLinks.Select(x => new Uri(x)).ToList();

            IconPicker.ItemsSource = iconList;
            IconPicker.SelectedIndex = 0;

            // Set up a new kml document and kml layer.
            ResetKml();
        }

        private void ResetKml()
        {
            // Clear any existing layers from the map.
            MyMapView.Map.OperationalLayers.Clear();

            // Reset the most recently placed placemark.
            _currentPlacemark = null;

            // Create a new KML document.
            _kmlDocument = new KmlDocument() { Name = "KML Sample Document" };

            // Create a KML dataset using the KML document.
            _kmlDataset = new KmlDataset(_kmlDocument);

            // Create the KML layer using the KML dataset.
            _kmlLayer = new KmlLayer(_kmlDataset);

            // Add the KML layer to the map.
            MyMapView.Map.OperationalLayers.Add(_kmlLayer);
        }

        private void Edit_Click(object sender, RoutedEventArgs e)
        {
            try
            {
                // Hide the base UI and enable the complete button.
                ShapesPanel.Visibility = Visibility.Hidden;
                CompleteButton.Visibility = Visibility.Visible;
                SaveResetGrid.IsEnabled = false;

                // Set the creation mode and UI based on which button called this method.
                switch (((Button)sender).Name)
                {
                    case nameof(PointButton):
                        _geometryType = GeometryType.Point;
                        InstructionsText.Text = "Tap to add a point.";
                        StyleText.Text = "Select an icon for the placemark.";
                        break;

                    case nameof(PolylineButton):
                        _geometryType = GeometryType.Polyline;
                        InstructionsText.Text = "Tap to add a vertex.";
                        StyleText.Text = "Select a color for the placemark.";
                        break;

                    case nameof(PolygonButton):
                        _geometryType = GeometryType.Polygon;
                        InstructionsText.Text = "Tap to add a vertex.";
                        StyleText.Text = "Select a color for the placemark.";
                        break;

                    default:
                        return;
                }

                // Start the geometry editor.
                MyMapView.GeometryEditor.Start(_geometryType);
            }
            catch (ArgumentException)
            {
                MessageBox.Show("Unsupported Geometry", "Error");
            }
        }

        private void Apply_Style_Click(object sender, RoutedEventArgs e)
        {
            // Create a new style for the placemark.
            _currentPlacemark.Style = new KmlStyle();

            // Set the style for that Placemark.
            switch (_currentPlacemark.GraphicType)
            {
                // Create a KmlIconStyle using the selected icon.
                case KmlGraphicType.Point:
                    _currentPlacemark.Style.IconStyle = new KmlIconStyle(new KmlIcon((Uri)IconPicker.SelectedItem), 1.0);
                    break;

                // Create a KmlLineStyle using the selected color value.
                case KmlGraphicType.Polyline:
                    _currentPlacemark.Style.LineStyle = new KmlLineStyle((Color)ColorPicker.SelectedItem, 8);
                    break;

                // Create a KmlPolygonStyle using the selected color value.
                case KmlGraphicType.Polygon:
                    _currentPlacemark.Style.PolygonStyle = new KmlPolygonStyle((Color)ColorPicker.SelectedItem);
                    _currentPlacemark.Style.PolygonStyle.IsFilled = true;
                    _currentPlacemark.Style.PolygonStyle.IsOutlined = false;
                    break;
            }

            // Reset the UI.
            StyleBorder.Visibility = Visibility.Collapsed;
            MainUI.IsEnabled = true;
        }

        private void No_Style_Click(object sender, RoutedEventArgs e)
        {
            // Reset the UI.
            StyleBorder.Visibility = Visibility.Collapsed;
            MainUI.IsEnabled = true;
        }

        private void Complete_Click(object sender, RoutedEventArgs e)
        {
            try
            {
                // Get the user-drawn geometry.
                Geometry geometry = MyMapView.GeometryEditor.Stop();

                // Hold a reference for the new placemark geometry.
                KmlGeometry kmlGeometry;

                // Check to see if a geometry has been drawn.
                if (!geometry.IsEmpty)
                {

                    if (MyMapView.SpatialReference != null &&
                        geometry.SpatialReference != MyMapView.SpatialReference &&
                        GeometryEngine.Project(geometry, MyMapView.SpatialReference) is Geometry projectedGeometry)
                    {
                        // Project the geometry to WGS84 (WGS84 is required by the KML standard).
                        projectedGeometry = geometry.Project(SpatialReferences.Wgs84);

                        // Create a KmlGeometry using the projected geometry.
                        kmlGeometry = new KmlGeometry(projectedGeometry, KmlAltitudeMode.ClampToGround);
                    }
                    else
                    {
                        // Create a KmlGeometry using the user-drawn geometry.
                        kmlGeometry = new KmlGeometry(geometry, KmlAltitudeMode.ClampToGround);
                    }

                    // Create a new placemark.
                    _currentPlacemark = new KmlPlacemark(kmlGeometry);

                    // Add the placemark to the KmlDocument.
                    _kmlDocument.ChildNodes.Add(_currentPlacemark);

                    // Enable the style editing UI.
                    StyleBorder.Visibility = Visibility.Visible;
                    MainUI.IsEnabled = false;

                    // Choose whether to enable the icon picker or color picker.
                    IconPicker.Visibility = _geometryType == GeometryType.Point ? Visibility.Visible : Visibility.Collapsed;
                    ColorPicker.Visibility = _geometryType != GeometryType.Point ? Visibility.Visible : Visibility.Collapsed;
                }
            }
            catch (Exception ex)
            {
                Debug.WriteLine(ex.Message);
            }
            finally
            {
                // Reset the UI.
                ShapesPanel.Visibility = Visibility.Visible;
                CompleteButton.Visibility = Visibility.Collapsed;
                InstructionsText.Text = "Select the type of feature you would like to add.";

                // Enable the save and reset buttons.
                SaveResetGrid.IsEnabled = true;
            }
        }

        private async void Save_Click(object sender, RoutedEventArgs e)
        {
            // Open a save dialog for the user.
            SaveFileDialog saveFileDialog = new SaveFileDialog();
            saveFileDialog.Filter = "kmz files (*.kmz)|*.kmz";
            saveFileDialog.FilterIndex = 1;

            if (saveFileDialog.ShowDialog() == true)
            {
                try
                {
                    // Write the KML document to the chosen path.
                    await _kmlDocument.SaveAsAsync(saveFileDialog.FileName);
                    MessageBox.Show("Item saved.");
                }
                catch
                {
                    MessageBox.Show("File not saved.");
                }
            }
        }

        private void Reset_Click(object sender, RoutedEventArgs e)
        {
            ResetKml();
        }
    }
}

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