Skip to content
View on GitHubSample viewer app

List the contents of a KML file.

screenshot

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 list of buttons. Select a node to zoom to that node and see its child nodes, if it has any. 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 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 KmlViewpoint or Extent to determine a viewpoint and set the SceneView object's viewpoint to it.

Relevant API

  • KmlContainer
  • KmlDataset
  • KmlDocument
  • KmlFolder
  • KmlGroundOverlay
  • KmlLayer
  • KmlNetworkLink
  • KmlNode
  • KmlPhotoOverlay
  • KmlPlacemark
  • KmlScreenOverlay
  • KmlViewpoint

Offline data

To set up the sample's offline data, see the Use offline data in the samples section of the Qt Samples repository overview.

Link Local Location
Esri KML Sample Data <userhome>/ArcGIS/Runtime/Data/kml/esri_kml_sample_data.kmz

About the data

This is an example KML file meant to demonstrate how the ArcGIS Maps SDK for Native Apps supports several common features.

Tags

Keyhole, KML, KMZ, layers, OGC

Sample Code

ListKmlContents.cppListKmlContents.cppListKmlContents.hListKmlContents.qml
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
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
// [WriteFile Name=ListKmlContents, Category=Layers]
// [Legal]
// Copyright 2020 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.
// [Legal]

#ifdef PCH_BUILD
#include "pch.hpp"
#endif // PCH_BUILD

// sample headers
#include "ListKmlContents.h"

// ArcGIS Maps SDK headers
#include "ArcGISTiledElevationSource.h"
#include "Camera.h"
#include "ElevationSourceListModel.h"
#include "Envelope.h"
#include "Error.h"
#include "KmlContainer.h"
#include "KmlDataset.h"
#include "KmlLayer.h"
#include "KmlNetworkLink.h"
#include "KmlNode.h"
#include "KmlNodeListModel.h"
#include "KmlViewpoint.h"
#include "LayerListModel.h"
#include "MapTypes.h"
#include "Point.h"
#include "Scene.h"
#include "SceneQuickView.h"
#include "SpatialReference.h"
#include "Surface.h"
#include "Viewpoint.h"

// Qt headers
#include <QFuture>
#include <QStandardPaths>
#include <QUuid>

// C++ Headers
#include <algorithm>
#include <utility>

using namespace Esri::ArcGISRuntime;

// helper method to get cross platform data path
namespace
{
  QString defaultDataPath()
  {
    QString dataPath;

#ifdef Q_OS_IOS
    dataPath = QStandardPaths::writableLocation(QStandardPaths::DocumentsLocation);
#else
    dataPath = QStandardPaths::writableLocation(QStandardPaths::HomeLocation);
#endif

    return dataPath;
  }
} // namespace

ListKmlContents::ListKmlContents(QObject* parent /* = nullptr */) :
  QObject(parent),
  m_scene(new Scene(BasemapStyle::ArcGISImagery, this))
{
  // create a new elevation source from Terrain3D REST service
  ArcGISTiledElevationSource* elevationSource =
    new ArcGISTiledElevationSource(QUrl("https://elevation3d.arcgis.com/arcgis/rest/services/WorldElevation3D/Terrain3D/ImageServer"), this);

  // add the elevation source to the scene to display elevation
  m_scene->baseSurface()->elevationSources()->append(elevationSource);

  const QString filepath = defaultDataPath() + "/ArcGIS/Runtime/Data/kml/esri_kml_sample_data.kmz";

  // create new KML layer
  m_kmlDataset = new KmlDataset(filepath, this);
  KmlLayer* kmlLayer = new KmlLayer(m_kmlDataset, this);
  m_scene->operationalLayers()->append(kmlLayer);

  connect(m_kmlDataset, &KmlDataset::doneLoading, this, [this](const Error& loadError)
  {
    if (!loadError.isEmpty())
    {
      qDebug() << loadError.message() << loadError.additionalMessage();
      return;
    }

    // recursively build tree to display KML contents
    const QList<KmlNode*> nodes = m_kmlDataset->rootNodes();
    buildTree(nodes);

    // if at top node, then display children
    if (!m_kmlNodesList.isEmpty() && m_kmlNodesList[0]->parentNode() == nullptr)
    {
      m_currentNode = m_kmlNodesList[0];
      emit currentNodeChanged();
      emit levelNodeNamesChanged();
    }
  });
}

QString ListKmlContents::getKmlNodeType(KmlNode* node)
{
  if (node == nullptr)
  {
    return "";
  }

  QString type = "";
  switch (node->kmlNodeType())
  {
    case KmlNodeType::KmlDocument:
      type = "KmlDocument";
      break;
    case KmlNodeType::KmlFolder:
      type = "KmlFolder";
      break;
    case KmlNodeType::KmlNetworkLink:
      type = "KmlNetworkLink";
      break;
    case KmlNodeType::KmlPlacemark:
      type = "KmlPlacemark";
      break;
    case KmlNodeType::KmlPhotoOverlay:
      type = "KmlPhotoOverlay";
      break;
    case KmlNodeType::KmlGroundOverlay:
      type = "KmlGroundOverlay";
      break;
    case KmlNodeType::KmlScreenOverlay:
      type = "KmlScreenOverlay";
      break;
    case KmlNodeType::KmlTour:
      type = "KmlTour";
      break;
    default:
      return "";
  }
  return type;
}

// recursively build string to indicate node's ancestors
QStringList ListKmlContents::buildPathLabel(KmlNode* node) const
{
  if (node != nullptr)
  {
    return buildPathLabel(node->parentNode()) << node->name();
  }
  return QStringList{};
}

void ListKmlContents::displayPreviousLevel()
{
  KmlNode* parentNode = m_currentNode->parentNode();
  if (parentNode == nullptr)
  {
    return;
  }

  KmlNode* grandparentNode = parentNode->parentNode();

  if (grandparentNode != nullptr)
  {
    m_currentNode = grandparentNode;
  }
  // if grandparent node is nullptr, then at top of tree
  else
  {
    m_currentNode = parentNode;
  }
  emit currentNodeChanged();
  emit labelTextChanged();
  emit levelNodeNamesChanged();
}

// display selected node on sceneview and show its children
void ListKmlContents::processSelectedNode(const QString& nodeName)
{
  // extract the node's name from the string, formatted "name - nodeType"
  QString extractedNodeName = nodeName;
  if (nodeName.contains(" - "))
  {
    int ind = nodeName.lastIndexOf(" - ");
    extractedNodeName = nodeName.left(ind);
  }

  // find node in the list
  for (KmlNode* node : std::as_const(m_kmlNodesList))
  {
    if (extractedNodeName == node->name())
    {
      // update current node
      m_currentNode = node;
      emit currentNodeChanged();
      emit labelTextChanged();
      emit levelNodeNamesChanged();

      // if displaying end-nodes, change m_currentNode to first end-node for correct behavior of back button
      if (KmlContainer* container = dynamic_cast<KmlContainer*>(m_currentNode))
      {
        if (!hasGrandchildren(container))
        {
          m_currentNode = container->childNodesListModel()->at(0);
          emit currentNodeChanged();
        }
      }

      // If node has viewpoint, set view to that viewpoint. Otherwise, create a viewpoint to encompass node's geometry
      KmlViewpoint nodeViewpoint = node->viewpoint();

      if (nodeViewpoint.isEmpty())
      {
        // if no viewpoint, set view to encompass node's geometry
        const Envelope nodeExtent = node->extent();
        if (nodeExtent.isValid())
        {
          if (nodeExtent.width() == 0 && nodeExtent.height() == 0)
          {
            nodeViewpoint = KmlViewpoint::createLookAtViewpoint(nodeExtent.center(), 0, 45, 1000, KmlAltitudeMode::RelativeToGround);
          }
          else
          {
            nodeViewpoint = KmlViewpoint::createWithViewpoint(Viewpoint(nodeExtent));
          }
        }
      }
      // If nodeViewpoint is still empty, this method is a no-op and will not change the current view
      setSceneViewCameraFromKmlViewpoint(nodeViewpoint);
      break;
    }
  }
}

void ListKmlContents::setSceneViewCameraFromKmlViewpoint(const KmlViewpoint& viewpoint)
{
  if (viewpoint.isEmpty())
  {
    return;
  }

  const Camera camera = [&viewpoint]() -> Camera
  {
    switch (viewpoint.type())
    {
      case KmlViewpointType::LookAt:
        return Camera(viewpoint.location(), viewpoint.range(), viewpoint.heading(), viewpoint.pitch(), viewpoint.roll());
      case KmlViewpointType::Camera:
        return Camera(viewpoint.location(), viewpoint.heading(), viewpoint.pitch(), viewpoint.roll());
      default:
        qWarning("Unexpected KmlViewpointType");
        return Camera();
    }
  }();

  if (!camera.location().isValid())
  {
    qWarning() << "Invalid camera location in KML viewpoint";
    return;
  }

  if (viewpoint.altitudeMode() != KmlAltitudeMode::Absolute)
  {
    // Get elevation at camera location
    m_scene->baseSurface()
      ->applyElevationAsync(viewpoint.location())
      .then(this, [camera, this](const Geometry& locationOnSurface)
    {
      const double deltaElevation = Point(locationOnSurface).z();
      const Camera raisedCamera = camera.elevate(deltaElevation);
      m_sceneView->setViewpointCameraAsync(raisedCamera, 1);
    });
  }
  else
  {
    m_sceneView->setViewpointCameraAsync(camera, 1);
  }
}

// recursively build list of all KML nodes
void ListKmlContents::buildTree(const QList<KmlNode*>& rootNodes)
{
  for (KmlNode* node : std::as_const(rootNodes))
  {
    // some nodes have default visibility set to false
    node->setVisible(true);
    m_kmlNodesList << node;

    if (KmlContainer* container = dynamic_cast<KmlContainer*>(node))
    {
      QList<KmlNode*> childNodes;
      for (KmlNode* childNode : *(container->childNodesListModel()))
      {
        childNodes << childNode;
      }
      if (!childNodes.isEmpty())
      {
        buildTree(childNodes);
      }
    }
    else if (KmlNetworkLink* networkLink = dynamic_cast<KmlNetworkLink*>(node))
    {
      const QList<KmlNode*> childNodes = networkLink->childNodes();
      buildTree(childNodes);
    }
  }
}

ListKmlContents::~ListKmlContents() = default;

void ListKmlContents::init()
{
  // Register classes for QML
  qmlRegisterType<SceneQuickView>("Esri.Samples", 1, 0, "SceneView");
  qmlRegisterType<ListKmlContents>("Esri.Samples", 1, 0, "ListKmlContentsSample");
}

SceneQuickView* ListKmlContents::sceneView() const
{
  return m_sceneView;
}

// Set the view (created in QML)
void ListKmlContents::setSceneView(SceneQuickView* sceneView)
{
  if (!sceneView || sceneView == m_sceneView)
  {
    return;
  }

  m_sceneView = sceneView;
  m_sceneView->setArcGISScene(m_scene);

  emit sceneViewChanged();
}

QStringList ListKmlContents::levelNodeNames()
{
  if (m_currentNode == nullptr)
  {
    return {};
  }

  QStringList nodeNames = {};

  // if node is not a container, m_levelNodeNames will be unchanged
  if (KmlContainer* container = dynamic_cast<KmlContainer*>(m_currentNode))
  {
    // for current level, get names of child nodes
    for (KmlNode* node : *(container->childNodesListModel()))
    {
      QString str = node->name() + " - " + getKmlNodeType(node);

      // if node has children, add ">" to indicate further levels
      if (!node->children().isEmpty())
      {
        str.append(" >");
      }
      nodeNames << str;
    }
    m_levelNodeNames = nodeNames;
  }
  return m_levelNodeNames;
}

bool ListKmlContents::hasGrandchildren(KmlContainer* container) const
{
  return std::any_of(container->childNodesListModel()->begin(), container->childNodesListModel()->end(), [](KmlNode* node)
  {
    if (KmlContainer* container = dynamic_cast<KmlContainer*>(node))
    {
      return !container->children().isEmpty();
    }
    else if (KmlNetworkLink* networkLink = dynamic_cast<KmlNetworkLink*>(node))
    {
      return !networkLink->childNodes().isEmpty();
    }
    return false;
  });
}

QString ListKmlContents::labelText() const
{
  return buildPathLabel(m_currentNode).join(" > ");
}

bool ListKmlContents::isTopLevel() const
{
  return (!m_currentNode || !m_currentNode->parentNode());
}

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