Create features from preset and group shared templates.

Use case
Preset and group shared templates support guided, repeatable, high-quality editing. Preset templates place predefined feature arrangements, while group templates create feature sets relative to a user-defined base geometry. By automatically applying attributes, symbology, geometry settings, and feature relationships/associations, they help field staff create consistent, fully configured assets with only a few choices.
How to use the sample
Hover over a shared template to view its description. Select a template and click on the map to place the geometry. Choose “Complete” to create and add the features locally, or “Cancel” to discard the sketch.
How it works
- Create a map using the URL to a web map.
- Determine the
SharedTemplateSourceby inspecting map layers, identifyingFeatureLayerinstances backed by aServiceFeatureTable, and retrieving theirServiceGeodatabase. - Call
SharedTemplateSource::querySharedTemplatesAsync()to populate a template picker. Store each template’slayerId, display its name and type, and use native contextual help to show its description. - Call
SharedTemplate::createSwatchAsync(layerId)to generate a swatch image for each template, falling back to a default image when a swatch is unavailable. - Call
SharedTemplate::defaultConstructionTool(layerId)to get the template’s default construction method. Use itsGeometryConstructionTool::toolType()to choose whether theGeometryEditordraws a point or polyline. - After the user selects “Complete”, call
GeometryEditor::stop()and use the returned geometry to create features withSharedTemplateSource::createFeaturesAsync(sharedTemplate, geometry). Then callSharedTemplateSource::addFeaturesAsync()to add the resulting feature set to the geodatabase.
Relevant API
- GeometryConstructionTool
- GeometryEditor
- ServiceGeodatabase
- SharedTemplate
- SharedTemplateFeatureCreationSet
- SharedTemplateQueryParameters
- SharedTemplateSource
About the data
- The sample uses the Parks and Grounds Assets web map.
Tags
edit, feature, group, preset, shared template, shared template source, template
Sample code
// [WriteFile Name=AddFeaturesWithSharedTemplates, Category=EditData]// [Legal]// Copyright 2026 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 "AddFeaturesWithSharedTemplates.h"
// ArcGIS Maps SDK headers#include "Error.h"#include "ErrorException.h"#include "FeatureLayer.h"#include "GeodatabaseTypes.h"#include "Geometry.h"#include "GeometryBuilder.h"#include "GeometryConstructionTool.h"#include "GeometryEditor.h"#include "GeometryTypes.h"#include "Layer.h"#include "LayerListModel.h"#include "Map.h"#include "MapQuickView.h"#include "PortalItem.h"#include "ServiceFeatureTable.h"#include "ServiceGeodatabase.h"#include "SharedTemplate.h"#include "SharedTemplateFeatureCreationSet.h"#include "VertexTool.h"
// Qt headers#include <QBuffer>#include <QDebug>#include <QFuture>#include <QImage>#include <QMap>#include <QVariantMap>
// STL headers#include <memory>
using namespace Esri::ArcGISRuntime;
namespace{ const QString createFeatureError = "Unable to create or add features.";} // namespace
AddFeaturesWithSharedTemplates::AddFeaturesWithSharedTemplates(QObject* parent) : QObject(parent), m_map(new Map(new PortalItem(QStringLiteral("b635be46dfb545b888077389ac7f0962"), this), this)), m_geometryEditor(new GeometryEditor(this)), m_statusText("Loading shared templates..."){ m_geometryEditor->setTool(new VertexTool(this)); connect(m_geometryEditor, &GeometryEditor::geometryChanged, this, &AddFeaturesWithSharedTemplates::updateCanComplete_); connect(m_geometryEditor, &GeometryEditor::isStartedChanged, this, &AddFeaturesWithSharedTemplates::updateCanComplete_);
connect(m_map, &Map::doneLoading, this, [this](const Error& error) { if (!error.isEmpty()) { reportError_("Unable to load templates.", error.message()); return; }
for (Layer* layer : *m_map->operationalLayers()) { FeatureLayer* featureLayer = qobject_cast<FeatureLayer*>(layer); ServiceFeatureTable* table = featureLayer ? qobject_cast<ServiceFeatureTable*>(featureLayer->featureTable()) : nullptr; if (table && table->serviceGeodatabase()) { m_serviceGeodatabase = table->serviceGeodatabase(); loadTemplates_(); return; } } reportError_("Unable to load templates.", "The map does not contain a shared template source."); });}
AddFeaturesWithSharedTemplates::~AddFeaturesWithSharedTemplates() = default;
void AddFeaturesWithSharedTemplates::init(){ qmlRegisterType<MapQuickView>("Esri.Samples", 1, 0, "MapView"); qmlRegisterType<AddFeaturesWithSharedTemplates>("Esri.Samples", 1, 0, "AddFeaturesWithSharedTemplatesSample");}
MapQuickView* AddFeaturesWithSharedTemplates::mapView() const{ return m_mapView;}
void AddFeaturesWithSharedTemplates::setMapView(MapQuickView* mapView){ if (!mapView || m_mapView == mapView) { return; } m_mapView = mapView; m_mapView->setMap(m_map); m_mapView->setGeometryEditor(m_geometryEditor); emit mapViewChanged();}
bool AddFeaturesWithSharedTemplates::sketchInProgress() const{ return m_activeTemplateIndex >= 0;}
void AddFeaturesWithSharedTemplates::loadTemplates_(){ m_serviceGeodatabase->querySharedTemplatesAsync(nullptr, this) .then(this, [this](const QMap<qint64, QList<SharedTemplate*>>& templatesByLayer) { for (QMap<qint64, QList<SharedTemplate*>>::const_iterator it = templatesByLayer.cbegin(); it != templatesByLayer.cend(); ++it) { for (SharedTemplate* sharedTemplate : it.value()) { const SharedTemplateType type = sharedTemplate->type(); if (type != SharedTemplateType::Preset && type != SharedTemplateType::Group) { continue; } m_templateItems.append({sharedTemplate, it.key()}); m_templates.append(QVariantMap{ {QStringLiteral("name"), sharedTemplate->name()}, {QStringLiteral("kind"), type == SharedTemplateType::Preset ? "Preset" : "Group"}, {QStringLiteral("description"), sharedTemplate->description()}, {QStringLiteral("swatch"), QString()}, }); } } emit templatesChanged(); if (!m_ready) { m_ready = true; emit readyChanged(); } finishOperation_(m_templates.isEmpty() ? "This map has no preset or group shared templates." : "Open Shared Templates and select a template to create features."); for (qsizetype index = 0; index < m_templateItems.size(); ++index) { createSwatch_(index); } }) .onFailed(this, [this](const ErrorException& error) { reportError_("Unable to load templates.", error.error().message()); });}
void AddFeaturesWithSharedTemplates::createSwatch_(qsizetype index){ const TemplateItem& item = m_templateItems.at(index); item.sharedTemplate->createSwatchAsync(item.layerId) .then(this, [this, index](const QImage& image) { if (image.isNull()) { qWarning() << "Shared template has no swatch:" << m_templateItems.at(index).sharedTemplate->name(); return; } QBuffer buffer; if (!buffer.open(QIODevice::WriteOnly) || !image.save(&buffer, "PNG")) { qWarning() << "Unable to encode shared template swatch."; return; } QVariantMap entry = m_templates.at(index).toMap(); entry.insert(QStringLiteral("swatch"), QStringLiteral("data:image/png;base64,") + QString::fromLatin1(buffer.data().toBase64())); m_templates[index] = entry; emit templatesChanged(); }) .onFailed(this, [this, index](const ErrorException& error) { // A swatch failure leaves the visible placeholder and must not prevent template selection. qDebug() << "Unable to create shared template swatch:" << m_templateItems.at(index).sharedTemplate->name() << "layer ID:" << m_templateItems.at(index).layerId << error.error(); });}
void AddFeaturesWithSharedTemplates::startDrawing(int index){ if (m_busy || sketchInProgress()) { return; } if (index < 0 || index >= m_templateItems.size()) { reportError_("Unable to start drawing.", "Select an available shared template."); return; } const TemplateItem& item = m_templateItems.at(index); GeometryConstructionTool* tool = item.sharedTemplate->defaultConstructionTool(item.layerId); if (!tool || (tool->toolType() != GeometryConstructionToolType::Point && tool->toolType() != GeometryConstructionToolType::Line)) { reportError_("Unable to start drawing.", "The template's default construction tool is not supported by this sample."); return; } const bool isPoint = tool->toolType() == GeometryConstructionToolType::Point; m_activeTemplateIndex = index; setStatusText_(isPoint ? "Place a point, then tap Complete or Cancel." : "Sketch a line, then tap Complete or Cancel."); m_geometryEditor->start(isPoint ? GeometryType::Point : GeometryType::Polyline); emit sketchInProgressChanged();}
void AddFeaturesWithSharedTemplates::cancelDrawing(){ if (m_busy || !sketchInProgress()) { return; } m_geometryEditor->stop(); m_activeTemplateIndex = -1; emit sketchInProgressChanged(); setStatusText_("Draw canceled.");}
void AddFeaturesWithSharedTemplates::completeDrawing(){ if (m_busy || !sketchInProgress()) { return; } if (!m_canComplete) { setStatusText_("Draw a valid geometry, then tap Complete or Cancel."); return; } SharedTemplate* sharedTemplate = m_templateItems.at(m_activeTemplateIndex).sharedTemplate; setBusy_(true); const Geometry geometry = m_geometryEditor->stop(); m_activeTemplateIndex = -1; emit sketchInProgressChanged(); if (geometry.isEmpty()) { finishOperation_("No geometry was drawn."); return; } setStatusText_("Creating features...");
m_serviceGeodatabase->createFeaturesAsync(sharedTemplate, geometry, this) .then(this, [this](SharedTemplateFeatureCreationSet* result) { if (!result) { reportError_(createFeatureError, "No feature creation set was returned."); return; } const std::shared_ptr<SharedTemplateFeatureCreationSet> creationSet(result, [](SharedTemplateFeatureCreationSet* value) { value->deleteLater(); }); creationSet->setParent(nullptr); m_serviceGeodatabase->addFeaturesAsync(creationSet.get()) .then(this, [this, creationSet] { finishOperation_("Features added."); }) .onFailed(this, [this, creationSet](const ErrorException& error) { reportError_(createFeatureError, error.error().message()); }); }) .onFailed(this, [this](const ErrorException& error) { reportError_(createFeatureError, error.error().message()); });}
void AddFeaturesWithSharedTemplates::updateCanComplete_(){ bool canComplete = false; if (m_geometryEditor->isStarted()) { const std::unique_ptr<GeometryBuilder> builder(GeometryBuilder::create(m_geometryEditor->geometry())); canComplete = builder && builder->isSketchValid(); } if (m_canComplete != canComplete) { m_canComplete = canComplete; emit canCompleteChanged(); }}
void AddFeaturesWithSharedTemplates::setStatusText_(const QString& status){ if (m_statusText != status) { m_statusText = status; emit statusTextChanged(); }}
void AddFeaturesWithSharedTemplates::setBusy_(bool busy){ if (m_busy != busy) { m_busy = busy; emit busyChanged(); }}
void AddFeaturesWithSharedTemplates::finishOperation_(const QString& status){ setStatusText_(status); setBusy_(false);}
void AddFeaturesWithSharedTemplates::reportError_(const QString& status, const QString& message){ finishOperation_(status); qWarning() << status << message; emit errorOccurred(message);}// [WriteFile Name=AddFeaturesWithSharedTemplates, Category=EditData]// [Legal]// Copyright 2026 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 ADDFEATURESWITHSHAREDTEMPLATES_H#define ADDFEATURESWITHSHAREDTEMPLATES_H
// Qt headers#include <QList>#include <QObject>#include <QString>#include <QVariantList>
namespace Esri::ArcGISRuntime{ class GeometryEditor; class Map; class MapQuickView; class ServiceGeodatabase; class SharedTemplate;} // namespace Esri::ArcGISRuntime
Q_MOC_INCLUDE("MapQuickView.h")
class AddFeaturesWithSharedTemplates : public QObject{ Q_OBJECT
Q_PROPERTY(Esri::ArcGISRuntime::MapQuickView* mapView READ mapView WRITE setMapView NOTIFY mapViewChanged) Q_PROPERTY(QVariantList templates MEMBER m_templates NOTIFY templatesChanged) Q_PROPERTY(QString statusText MEMBER m_statusText NOTIFY statusTextChanged) Q_PROPERTY(bool busy MEMBER m_busy NOTIFY busyChanged) Q_PROPERTY(bool ready MEMBER m_ready NOTIFY readyChanged) Q_PROPERTY(bool sketchInProgress READ sketchInProgress NOTIFY sketchInProgressChanged) Q_PROPERTY(bool canComplete MEMBER m_canComplete NOTIFY canCompleteChanged)
public: explicit AddFeaturesWithSharedTemplates(QObject* parent = nullptr); ~AddFeaturesWithSharedTemplates() override;
static void init();
Q_INVOKABLE void startDrawing(int index); Q_INVOKABLE void cancelDrawing(); Q_INVOKABLE void completeDrawing();
Esri::ArcGISRuntime::MapQuickView* mapView() const; void setMapView(Esri::ArcGISRuntime::MapQuickView* mapView); bool sketchInProgress() const;
signals: void mapViewChanged(); void templatesChanged(); void statusTextChanged(); void busyChanged(); void readyChanged(); void sketchInProgressChanged(); void canCompleteChanged(); void errorOccurred(const QString& message);
private: Q_DISABLE_COPY_MOVE(AddFeaturesWithSharedTemplates)
struct TemplateItem { Esri::ArcGISRuntime::SharedTemplate* sharedTemplate = nullptr; qint64 layerId = 0; };
void loadTemplates_(); void createSwatch_(qsizetype index); void updateCanComplete_(); void setStatusText_(const QString& status); void setBusy_(bool busy); void finishOperation_(const QString& status); void reportError_(const QString& status, const QString& message);
Esri::ArcGISRuntime::Map* m_map = nullptr; Esri::ArcGISRuntime::MapQuickView* m_mapView = nullptr; Esri::ArcGISRuntime::GeometryEditor* m_geometryEditor = nullptr; Esri::ArcGISRuntime::ServiceGeodatabase* m_serviceGeodatabase = nullptr; QList<TemplateItem> m_templateItems; QVariantList m_templates; QString m_statusText; int m_activeTemplateIndex = -1; bool m_busy = true; bool m_ready = false; bool m_canComplete = false;};
#endif // ADDFEATURESWITHSHAREDTEMPLATES_H// [WriteFile Name=AddFeaturesWithSharedTemplates, Category=EditData]// [Legal]// Copyright 2026 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.Layoutsimport Esri.Samples
Item { id: root
readonly property bool sketchInProgress: sampleModel.sketchInProgress readonly property bool hasTemplates: sampleModel.templates.length > 0
component ToolbarButton: Button { Layout.minimumHeight: 44 focusPolicy: Qt.TabFocus }
MapView { id: mapView anchors.fill: parent Component.onCompleted: forceActiveFocus() }
AddFeaturesWithSharedTemplatesSample { id: sampleModel mapView: mapView onErrorOccurred: function (message) { errorMessage.text = message; errorDialog.open(); } }
Pane { id: statusPanel anchors { top: parent.top left: parent.left right: parent.right } padding: 8 visible: !noTemplatesPanel.visible
RowLayout { width: parent.width ColumnLayout { Layout.fillWidth: true Label { text: sampleModel.statusText wrapMode: Text.WordWrap horizontalAlignment: Text.AlignHCenter Layout.fillWidth: true } Label { visible: !sampleModel.busy && !root.sketchInProgress && root.hasTemplates && text !== sampleModel.statusText text: qsTr("Open Shared Templates and select a template to create features.") wrapMode: Text.WordWrap horizontalAlignment: Text.AlignHCenter Layout.fillWidth: true } } BusyIndicator { running: sampleModel.busy visible: running Layout.preferredWidth: 32 Layout.preferredHeight: 32 } } }
Pane { id: noTemplatesPanel anchors.centerIn: parent width: Math.min(parent.width - 32, 360) visible: sampleModel.ready && !root.hasTemplates ColumnLayout { width: parent.width Label { text: qsTr("No Templates") font.bold: true horizontalAlignment: Text.AlignHCenter Layout.fillWidth: true } Label { text: qsTr("This map has no preset or group shared templates.") wrapMode: Text.WordWrap horizontalAlignment: Text.AlignHCenter Layout.fillWidth: true } } }
ToolBar { id: toolbar anchors { bottom: parent.bottom left: parent.left right: parent.right } topPadding: 12 bottomPadding: 12 leftPadding: 12 rightPadding: 12 visible: root.hasTemplates contentItem: RowLayout { spacing: 12 enabled: !sampleModel.busy ToolbarButton { text: qsTr("Cancel") visible: root.sketchInProgress onClicked: sampleModel.cancelDrawing() } Item { Layout.fillWidth: true } ToolbarButton { text: qsTr("Shared Templates") highlighted: true visible: !root.sketchInProgress onClicked: templatePicker.open() } Item { Layout.fillWidth: true } ToolbarButton { text: qsTr("Complete") highlighted: true visible: root.sketchInProgress enabled: sampleModel.canComplete onClicked: sampleModel.completeDrawing() } } }
Popup { id: templatePicker parent: root x: (parent.width - width) / 2 y: Math.max(8, toolbar.y - height - 8) width: Math.min(320, parent.width - 16) height: Math.min(templateContent.implicitHeight + topPadding + bottomPadding, Math.max(0, toolbar.y - statusPanel.height - 16)) padding: 12 focus: true closePolicy: Popup.CloseOnEscape | Popup.CloseOnPressOutside
contentItem: ScrollView { id: templateScroll clip: true contentWidth: availableWidth ScrollBar.horizontal.policy: ScrollBar.AlwaysOff
ColumnLayout { id: templateContent width: templateScroll.availableWidth spacing: 8 Label { text: qsTr("Shared Templates") font.bold: true Layout.fillWidth: true } Repeater { model: sampleModel.templates delegate: ItemDelegate { id: templateDelegate required property int index required property var modelData Layout.fillWidth: true enabled: !sampleModel.busy hoverEnabled: true focusPolicy: Qt.TabFocus Accessible.name: modelData.name Accessible.description: modelData.description ToolTip.visible: hovered || pressed || visualFocus ToolTip.text: modelData.description ToolTip.delay: 500 contentItem: RowLayout { spacing: 8 Item { Layout.preferredWidth: 36 Layout.preferredHeight: 36 Image { id: templateSwatch anchors.fill: parent source: templateDelegate.modelData.swatch fillMode: Image.PreserveAspectFit visible: status === Image.Ready } Label { anchors.centerIn: parent text: "+" font.pixelSize: 28 visible: templateSwatch.status !== Image.Ready Accessible.ignored: true } } ColumnLayout { Layout.fillWidth: true spacing: 2 Label { text: templateDelegate.modelData.name font.bold: true wrapMode: Text.WordWrap Layout.fillWidth: true } Label { text: templateDelegate.modelData.kind font.pixelSize: 12 } } } onClicked: { sampleModel.startDrawing(index); if (sampleModel.sketchInProgress) { templatePicker.close(); } } } } } } }
Dialog { id: errorDialog parent: root anchors.centerIn: parent width: Math.min(parent.width - 32, 420) height: Math.min(implicitHeight, Math.max(0, parent.height - 32)) title: qsTr("Error") modal: true standardButtons: Dialog.Ok contentItem: ScrollView { id: errorScroll clip: true contentWidth: availableWidth ScrollBar.horizontal.policy: ScrollBar.AlwaysOff
Label { id: errorMessage width: errorScroll.availableWidth wrapMode: Text.WordWrap } } }}