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

Use case
If you need to create and save data on the fly, you can use KML to create points, lines, and polygons and then 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
Application opens to a view of the Southwestern United States. Click on the “Save KMZ file” button to save the active KML document as a .kmz file on your system.
How it works
- Create a
Point,Polyline, andPolygon. - Create a
Graphicfor each and add it to theGraphicsOverlay - Create a
KmlGeometryobject using theGeometryfrom the point, line, and polygon. - Create a
KmlPlacemarkfor each kml geometry. - Set a
KmlStylefor each placemark. - Add all three kml placemarks to the
KmlDocument. - Save the kml document to a file using the
saveAsAsyncfunction.
Relevant API
- KmlDocument
- KmlGeometry
- KmlIcon
- KmlIconStyle
- KmlLineStyle
- KmlNode::saveAsAsync
- KmlPlacemark
- KmlPolygonStyle
- KmlStyle
Tags
Keyhole, KML, KMZ, OGC
Sample Code
// [WriteFile Name=CreateAndSaveKmlFile, Category=Layers]// [Legal]// 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.// [Legal]
#ifdef PCH_BUILD#include "pch.hpp"#endif // PCH_BUILD
// sample headers#include "CreateAndSaveKmlFile.h"
// ArcGIS Maps SDK headers#include "Envelope.h"#include "Error.h"#include "KmlDataset.h"#include "KmlDocument.h"#include "KmlGeometry.h"#include "KmlIcon.h"#include "KmlIconStyle.h"#include "KmlLayer.h"#include "KmlLineStyle.h"#include "KmlNodeListModel.h"#include "KmlPlacemark.h"#include "KmlPolygonStyle.h"#include "KmlStyle.h"#include "LayerListModel.h"#include "Map.h"#include "MapQuickView.h"#include "MapTypes.h"#include "PolygonBuilder.h"#include "PolylineBuilder.h"#include "SpatialReference.h"#include "Viewpoint.h"
// Qt headers#include <QFuture>
using namespace Esri::ArcGISRuntime;
CreateAndSaveKmlFile::CreateAndSaveKmlFile(QObject* parent /* = nullptr */): QObject(parent), m_map(new Map(BasemapStyle::ArcGISDarkGray, this)), m_kmlDocument(new KmlDocument(this)), m_point(createPoint()), m_polyline(createPolyline()), m_polygon(createPolygon()), m_kmlStyleWithPointStyle(createKmlStyleWithPointStyle()), m_kmlStyleWithLineStyle(createKmlStyleWithLineStyle()), m_kmlStyleWithPolygonStyle(createKmlStyleWithPolygonStyle()){ // set initial viewpoint m_map->setInitialViewpoint(Viewpoint(createEnvelope()));
connect(m_map, &Map::doneLoading, this, [this](const Error& e) { if (!e.isEmpty()) return;
m_kmlDataset = new KmlDataset(m_kmlDocument, this); m_kmlLayer = new KmlLayer(m_kmlDataset, this); addGraphics(); });
connect(m_kmlDocument, &KmlDocument::errorOccurred, this, [](const Error& e) { if (!e.isEmpty()) qDebug() << QString("Error: %1 - %2").arg(e.message(), e.additionalMessage()); });}
CreateAndSaveKmlFile::~CreateAndSaveKmlFile() = default;
void CreateAndSaveKmlFile::init(){ // Register the map view for QML qmlRegisterType<MapQuickView>("Esri.Samples", 1, 0, "MapView"); qmlRegisterType<CreateAndSaveKmlFile>("Esri.Samples", 1, 0, "CreateAndSaveKmlFileSample");}
MapQuickView* CreateAndSaveKmlFile::mapView() const{ return m_mapView;}
// Set the view (created in QML)void CreateAndSaveKmlFile::setMapView(MapQuickView* mapView){ if (!mapView || mapView == m_mapView) return;
m_mapView = mapView; m_mapView->setMap(m_map);
emit mapViewChanged();}
QString CreateAndSaveKmlFile::kmlFilePath() const{ return m_kmlFilePath;}
Geometry CreateAndSaveKmlFile::createPoint() const{ constexpr double x = -117.195800; constexpr double y = 34.056295; const SpatialReference spatialRef(4326);
return Point(x, y, spatialRef);}
Geometry CreateAndSaveKmlFile::createPolyline() const{ const SpatialReference spatialRef(4326); PolylineBuilder polylineBuilder(spatialRef);
polylineBuilder.addPoint(-119.992, 41.989); polylineBuilder.addPoint(-119.994, 38.994); polylineBuilder.addPoint(-114.620, 35.0);
return polylineBuilder.toGeometry();}
Geometry CreateAndSaveKmlFile::createPolygon() const{ const SpatialReference spatialRef(4326); PolygonBuilder polygonBuilder(spatialRef);
polygonBuilder.addPoint(-109.048, 40.998); polygonBuilder.addPoint(-102.047, 40.998); polygonBuilder.addPoint(-102.037, 36.989); polygonBuilder.addPoint(-109.048, 36.998);
return polygonBuilder.toGeometry();}
Geometry CreateAndSaveKmlFile::createEnvelope() const{ constexpr double xMin = -123.0; constexpr double yMin = 33.5; constexpr double xMax = -101.0; constexpr double yMax = 42.0;
const SpatialReference spatialRef(4326);
return Envelope(xMin, yMin, xMax, yMax, spatialRef);}
KmlStyle* CreateAndSaveKmlFile::createKmlStyleWithPointStyle(){ // Create Icon Style KmlIcon* icon = new KmlIcon(QUrl("https://static.arcgis.com/images/Symbols/Shapes/BlueStarLargeB.png"), this); KmlIconStyle* iconStyle = new KmlIconStyle(icon, 1.0, this);
// Create KmlStyle KmlStyle* kmlStyle = new KmlStyle(this); kmlStyle->setIconStyle(iconStyle);
return kmlStyle;}
KmlStyle* CreateAndSaveKmlFile::createKmlStyleWithLineStyle(){ // Create Line Style KmlLineStyle* lineStyle = new KmlLineStyle(QColor(Qt::red), 2, this);
// Create KmlStyle KmlStyle* kmlStyle = new KmlStyle(this); kmlStyle->setLineStyle(lineStyle);
return kmlStyle;}
KmlStyle* CreateAndSaveKmlFile::createKmlStyleWithPolygonStyle(){ // Create Polygon Style KmlPolygonStyle* polygonStyle = new KmlPolygonStyle(QColor(Qt::yellow), this);
// Create KmlStyle KmlStyle* kmlStyle = new KmlStyle(this); kmlStyle->setPolygonStyle(polygonStyle);
return kmlStyle;}
void CreateAndSaveKmlFile::addGraphics(){ addToKmlDocument(m_point, m_kmlStyleWithPointStyle); addToKmlDocument(m_polyline, m_kmlStyleWithLineStyle); addToKmlDocument(m_polygon, m_kmlStyleWithPolygonStyle);
m_mapView->map()->operationalLayers()->append(m_kmlLayer);}
void CreateAndSaveKmlFile::addToKmlDocument(const Geometry& geometry, KmlStyle* kmlStyle){ const KmlGeometry kmlGeometry = KmlGeometry(geometry, KmlAltitudeMode::ClampToGround); KmlPlacemark* placemark = new KmlPlacemark(kmlGeometry, this); placemark->setStyle(kmlStyle); m_kmlDocument->childNodesListModel()->append(placemark);}
void CreateAndSaveKmlFile::saveKml(){ m_kmlFilePath = QString{m_tempDir.path() + "/KmlSampleFile%1.kmz"}.arg(QDateTime::currentSecsSinceEpoch() % 1000); emit kmlFilePathChanged();
m_busy = true; emit busyChanged();
// Write the KML document to the chosen path. m_kmlDocument->saveAsAsync(m_kmlFilePath).then(this, [this]() { m_busy = false; emit busyChanged(); emit kmlSaveCompleted(); });}// [WriteFile Name=CreateAndSaveKmlFile, Category=Layers]// [Legal]// 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.// [Legal]
#ifndef CREATEANDSAVEKMLFILE_H#define CREATEANDSAVEKMLFILE_H
// ArcGIS Maps SDK headers#include "Geometry.h"#include "Point.h"#include "Polygon.h"#include "Polyline.h"
// Qt headers#include <QObject>#include <QTemporaryDir>#include <QUrl>
namespace Esri::ArcGISRuntime{class Map;class MapQuickView;class KmlDocument;class KmlDataset;class KmlLayer;class KmlStyle;}
Q_MOC_INCLUDE("MapQuickView.h")
class CreateAndSaveKmlFile : public QObject{ Q_OBJECT
Q_PROPERTY(Esri::ArcGISRuntime::MapQuickView* mapView READ mapView WRITE setMapView NOTIFY mapViewChanged) Q_PROPERTY(bool busy MEMBER m_busy NOTIFY busyChanged) Q_PROPERTY(QString kmlFilePath READ kmlFilePath NOTIFY kmlFilePathChanged)
public: explicit CreateAndSaveKmlFile(QObject* parent = nullptr); ~CreateAndSaveKmlFile();
static void init();
Q_INVOKABLE void saveKml();
signals: void mapViewChanged(); void busyChanged(); void kmlSaveCompleted(); void kmlFilePathChanged();
private: Esri::ArcGISRuntime::MapQuickView* mapView() const; void setMapView(Esri::ArcGISRuntime::MapQuickView* mapView); QString kmlFilePath() const;
Esri::ArcGISRuntime::Map* m_map = nullptr; Esri::ArcGISRuntime::MapQuickView* m_mapView = nullptr; Esri::ArcGISRuntime::KmlDocument* m_kmlDocument = nullptr; Esri::ArcGISRuntime::KmlDataset* m_kmlDataset = nullptr; Esri::ArcGISRuntime::KmlLayer* m_kmlLayer = nullptr; Esri::ArcGISRuntime::Point m_point; Esri::ArcGISRuntime::Polyline m_polyline; Esri::ArcGISRuntime::Polygon m_polygon; Esri::ArcGISRuntime::KmlStyle* m_kmlStyleWithPointStyle = nullptr; Esri::ArcGISRuntime::KmlStyle* m_kmlStyleWithLineStyle = nullptr; Esri::ArcGISRuntime::KmlStyle* m_kmlStyleWithPolygonStyle = nullptr;
bool m_busy = false;
Esri::ArcGISRuntime::Geometry createPoint() const; Esri::ArcGISRuntime::Geometry createPolyline() const; Esri::ArcGISRuntime::Geometry createPolygon() const; Esri::ArcGISRuntime::Geometry createEnvelope() const; Esri::ArcGISRuntime::KmlStyle* createKmlStyleWithPointStyle(); Esri::ArcGISRuntime::KmlStyle* createKmlStyleWithLineStyle(); Esri::ArcGISRuntime::KmlStyle* createKmlStyleWithPolygonStyle();
QTemporaryDir m_tempDir; QString m_kmlFilePath;
void addGraphics(); void addToKmlDocument(const Esri::ArcGISRuntime::Geometry& geometry, Esri::ArcGISRuntime::KmlStyle* kmlStyle);};
#endif // CREATEANDSAVEKMLFILE_H// [WriteFile Name=CreateAndSaveKmlFile, Category=Layers]// [Legal]// 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.// [Legal]
import QtQuickimport QtQuick.Controlsimport QtQuick.Dialogsimport Esri.Samples
Item {
// add a mapView component MapView { id: view anchors.fill: parent
Component.onCompleted: { // Set the focus on MapView to initially enable keyboard navigation forceActiveFocus(); } }
// Declare the C++ instance which creates the map etc. and supply the view CreateAndSaveKmlFileSample { id: model mapView: view
onKmlSaveCompleted: saveCompleteDialog.open(); }
Button { anchors{ left: parent.left top: parent.top margins: 3 } text: qsTr("Save kmz file")
enabled: model.busy === false
onClicked: { model.saveKml(); } }
BusyIndicator { anchors.centerIn: parent visible: model.busy }
Dialog { id: saveCompleteDialog anchors.centerIn: parent width: parent.width * .8 standardButtons: Dialog.Ok title: "Item saved to temporary location:" Label { text: model.kmlFilePath wrapMode: Text.Wrap width: parent.width } }}// [Legal]// 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.// [Legal]
// sample headers#include "CreateAndSaveKmlFile.h"
// ArcGIS Maps SDK headers#include "ArcGISRuntimeEnvironment.h"
// Qt headers#include <QDir>#include <QGuiApplication>#include <QQmlApplicationEngine>
// Platform specific headers#ifdef Q_OS_WIN#include <Windows.h>#endif
#define STRINGIZE(x) #x#define QUOTE(x) STRINGIZE(x)
int main(int argc, char *argv[]){ Esri::ArcGISRuntime::ArcGISRuntimeEnvironment::setUseLegacyAuthentication(false); QGuiApplication app(argc, argv); app.setApplicationName(QString("CreateAndSaveKmlFile"));
// Use of ArcGIS location services, such as basemap styles, geocoding, and routing services, // requires an access token. For more information see // https://links.esri.com/arcgis-runtime-security-auth.
// The following methods grant an access token:
// 1. User authentication: Grants a temporary access token associated with a user's ArcGIS account. // To generate a token, a user logs in to the app with an ArcGIS account that is part of an // organization in ArcGIS Online or ArcGIS Enterprise.
// 2. API key authentication: Get a long-lived access token that gives your application access to // ArcGIS location services. Go to the tutorial at https://links.esri.com/create-an-api-key. // Copy the API Key access token.
const QString accessToken = QString("");
if (accessToken.isEmpty()) { qWarning() << "Use of ArcGIS location services, such as the basemap styles service, requires" << "you to authenticate with an ArcGIS account or set the API Key property."; } else { Esri::ArcGISRuntime::ArcGISRuntimeEnvironment::setApiKey(accessToken); }
// Initialize the sample CreateAndSaveKmlFile::init();
QString arcGISRuntimeImportPath = QUOTE(ARCGIS_RUNTIME_IMPORT_PATH);
#if defined(LINUX_PLATFORM_REPLACEMENT) // on some linux platforms the string 'linux' is replaced with 1 // fix the replacement paths which were created QString replaceString = QUOTE(LINUX_PLATFORM_REPLACEMENT); arcGISRuntimeImportPath = arcGISRuntimeImportPath.replace(replaceString, "linux", Qt::CaseSensitive);#endif
// Initialize application view QQmlApplicationEngine engine; // Add the import Path engine.addImportPath(QDir(QCoreApplication::applicationDirPath()).filePath("qml")); // Add the Runtime and Extras path engine.addImportPath(arcGISRuntimeImportPath);
// Set the source engine.load(QUrl("qrc:/Samples/Layers/CreateAndSaveKmlFile/main.qml"));
return app.exec();}// Copyright 2019 ESRI//// All rights reserved under the copyright laws of the United States// and applicable international laws, treaties, and conventions.//// You may freely redistribute and use this sample code, with or// without modification, provided you include the original copyright// notice and use restrictions.//// See the Sample code usage restrictions document for further information.//
import QtQuick.Controlsimport Esri.Samples
ApplicationWindow { visible: true width: 800 height: 600
CreateAndSaveKmlFile { anchors.fill: parent }}