Use annotation sublayers to gain finer control of annotation layer subtypes.

Use case
Annotation, which differs from labels by having a fixed place and size, is typically only relevant at particular scales. Annotation sublayers allow for finer control of annotation by allowing properties (like visibility in the map and legend) to be set and others to be read (like name) on subtypes of an annotation layer.
An annotation dataset which marks valves as “Opened” or “Closed”, might be set to display the “Closed” valves over a broader range of scales than the “Opened” valves, if the “Closed” data is considered more relevant by the map’s author. Regardless, the user can be given a manual option to set visibility of annotation sublayers on and off, if required.
How to use the sample
Start the sample and take note of the visibility of the annotation. Zoom in and out to see the annotation turn on and off based on scale ranges set on the data.
Use the checkboxes to manually set “Open” and “Closed” annotation sublayers visibility to on or off.
How it works
- Load a
MobileMapPackagethat containsAnnotationSublayer. - Get the sublayers from the map package’s layers by calling
sublayer::subLayerContents()[i]. - You can toggle the visibility of each sublayer manually using
sublayer::setVisible(). - To determine if a sublayer is visible at the current scale of the
MapView, usesublayer::isVisibleAtScale(), by passing in the map’s current scale.
Relevant API
- AnnotationLayer
- AnnotationSublayer
- LayerContent
Offline Data
Read more about how to set up the sample’s offline data here.
| Link | Local Location |
|---|---|
| Gas Device Anno Mobile Map Package | <userhome>/ArcGIS/Runtime/Data/mmpk/GasDeviceAnno.mmpk |
About the data
The scale ranges were set by the map’s author using ArcGIS Pro:
- The “Open” annotation sublayer has its maximum scale set to 1:500 and its minimum scale set to 1:2000.
- The “Closed” annotation sublayer has no minimum or maximum scales set, so will be drawn at all scales.
Tags
annotation, scale, text, utilities, visualization
Sample Code
// [WriteFile Name=ControlAnnotationSublayerVisibility, Category=DisplayInformation]// [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 "ControlAnnotationSublayerVisibility.h"
// ArcGIS Maps SDK headers#include "AnnotationSublayer.h"#include "Error.h"#include "Layer.h"#include "LayerListModel.h"#include "Map.h"#include "MapQuickView.h"#include "MapTypes.h"#include "MobileMapPackage.h"
// Qt headers#include <QStandardPaths>#include <QtCore/qglobal.h>
using namespace Esri::ArcGISRuntime;
// helper method to get cross platform data pathnamespace{QString defaultDataPath(){ QString dataPath;
#ifdef Q_OS_IOS dataPath = QStandardPaths::writableLocation(QStandardPaths::DocumentsLocation);#else dataPath = QStandardPaths::writableLocation(QStandardPaths::HomeLocation);#endif
return dataPath;}
// sample MMPK locationconst QString sampleFileAnno {"/ArcGIS/Runtime/Data/mmpk/GasDeviceAnno.mmpk"};
} // namespace
ControlAnnotationSublayerVisibility::ControlAnnotationSublayerVisibility(QObject* parent /* = nullptr */): QObject(parent){ const QString dataPath = defaultDataPath() + sampleFileAnno;
// connect to the Mobile Map Package instance to know when errors occur connect(MobileMapPackage::instance(), &MobileMapPackage::errorOccurred, [](const Error& error) { if (error.isEmpty()) return;
qDebug() << QString("Error: %1 %2").arg(error.message(), error.additionalMessage()); });
// Load the MMPK createMapPackage(dataPath);}
ControlAnnotationSublayerVisibility::~ControlAnnotationSublayerVisibility() = default;
void ControlAnnotationSublayerVisibility::init(){ // Register the map view for QML qmlRegisterType<MapQuickView>("Esri.Samples", 1, 0, "MapView"); qmlRegisterType<ControlAnnotationSublayerVisibility>("Esri.Samples", 1, 0, "ControlAnnotationSublayerVisibilitySample");}
MapQuickView* ControlAnnotationSublayerVisibility::mapView() const{ return m_mapView;}
// Set the view (created in QML)void ControlAnnotationSublayerVisibility::setMapView(MapQuickView* mapView){ if (!mapView || mapView == m_mapView) return;
m_mapView = mapView; m_mapView->setMap(m_map);
connect(m_mapView, &MapQuickView::mapScaleChanged, this, [this]() { m_mapScale = m_mapView->mapScale(); emit mapScaleChanged();
if (!m_annotationSubLayerOpen) return;
m_visibleAtCurrentExtent = m_annotationSubLayerOpen->isVisibleAtScale(m_mapScale); emit visibleAtCurrentExtentChanged(); });
emit mapViewChanged();}
// create map packagevoid ControlAnnotationSublayerVisibility::createMapPackage(const QString& path){ //! [open mobile map package cpp snippet] // instatiate a mobile map package m_mobileMapPackage = new MobileMapPackage(path, this);
// wait for the mobile map package to load connect(m_mobileMapPackage, &MobileMapPackage::doneLoading, this, [this](const Error& error) { if (!error.isEmpty()) { qDebug() << QString("Package load error: %1 %2").arg(error.message(), error.additionalMessage()); return; }
if (!m_mobileMapPackage || !m_mapView || m_mobileMapPackage->maps().isEmpty()) return;
// The package contains a list of maps that could be shown in the UI for selection. // For simplicity, obtain the first map in the list of maps. // set the map on the map view to display m_mapView->setMap(m_mobileMapPackage->maps().at(0));
m_layerListModel = mapView()->map()->operationalLayers(); for (Layer* layer : *m_layerListModel) { if (layer->layerType() == LayerType::AnnotationLayer) { m_annoLayer = layer; connect(m_annoLayer, &Layer::doneLoading, this, [this](const Error& error) { if (!error.isEmpty()) { qDebug() << QString("Package load error: %1 %2").arg(error.message(), error.additionalMessage()); return; }
const auto contents = m_annoLayer->subLayerContents(); m_annotationSubLayerClosed = dynamic_cast<AnnotationSublayer*>(contents[0]); m_annotationSubLayerOpen = dynamic_cast<AnnotationSublayer*>(contents[1]); m_closedLayerText = m_annotationSubLayerClosed->name(); m_openLayerText = QString("%1 (1:%2 - 1:%3)").arg(m_annotationSubLayerOpen->name()).arg(m_annotationSubLayerOpen->maxScale()).arg(m_annotationSubLayerOpen->minScale()); emit openLayerTextChanged(); emit closedLayerTextChanged(); }); layer->load(); } } });
m_mobileMapPackage->load(); //! [open mobile map package cpp snippet]}
void ControlAnnotationSublayerVisibility::openLayerVisible(){ if (!m_annotationSubLayerOpen) return;
m_annotationSubLayerOpen->setVisible(!m_annotationSubLayerOpen->isVisible());}
void ControlAnnotationSublayerVisibility::closedLayerVisible(){ if (!m_annotationSubLayerClosed) return;
m_annotationSubLayerClosed->setVisible(!m_annotationSubLayerClosed->isVisible());}// [WriteFile Name=ControlAnnotationSublayerVisibility, Category=DisplayInformation]// [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 CONTROLANNOTATIONSUBLAYERVISIBILITY_H#define CONTROLANNOTATIONSUBLAYERVISIBILITY_H
// Qt headers#include <QObject>
namespace Esri::ArcGISRuntime{class Map;class MapQuickView;class MobileMapPackage;class AnnotationSublayer;class LayerListModel;class Layer;}
Q_MOC_INCLUDE("MapQuickView.h")
class ControlAnnotationSublayerVisibility : public QObject{ Q_OBJECT
Q_PROPERTY(Esri::ArcGISRuntime::MapQuickView* mapView READ mapView WRITE setMapView NOTIFY mapViewChanged) Q_PROPERTY(QString openLayerText MEMBER m_openLayerText NOTIFY openLayerTextChanged) Q_PROPERTY(QString closedLayerText MEMBER m_closedLayerText NOTIFY closedLayerTextChanged) Q_PROPERTY(double mapScale MEMBER m_mapScale NOTIFY mapScaleChanged()) Q_PROPERTY(bool visibleAtCurrentExtent MEMBER m_visibleAtCurrentExtent NOTIFY visibleAtCurrentExtentChanged())
public: explicit ControlAnnotationSublayerVisibility(QObject* parent = nullptr); ~ControlAnnotationSublayerVisibility();
static void init();
Q_INVOKABLE void openLayerVisible(); Q_INVOKABLE void closedLayerVisible();
signals: void mapViewChanged(); void openLayerTextChanged(); void closedLayerTextChanged(); void mapScaleChanged(); void visibleAtCurrentExtentChanged();
private: Esri::ArcGISRuntime::MapQuickView* mapView() const; void setMapView(Esri::ArcGISRuntime::MapQuickView* mapView); void createMapPackage(const QString& path);
Esri::ArcGISRuntime::Map* m_map = nullptr; Esri::ArcGISRuntime::MapQuickView* m_mapView = nullptr; Esri::ArcGISRuntime::MobileMapPackage* m_mobileMapPackage = nullptr; Esri::ArcGISRuntime::AnnotationSublayer* m_annotationSubLayerOpen = nullptr; Esri::ArcGISRuntime::AnnotationSublayer* m_annotationSubLayerClosed = nullptr; Esri::ArcGISRuntime::LayerListModel* m_layerListModel = nullptr; Esri::ArcGISRuntime::Layer* m_annoLayer = nullptr;
QString m_openLayerText; QString m_closedLayerText; bool m_visibleAtCurrentExtent; double m_mapScale = 0.0;};
#endif // CONTROLANNOTATIONSUBLAYERVISIBILITY_H// [WriteFile Name=ControlAnnotationSublayerVisibility, Category=DisplayInformation]// [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.Layoutsimport QtQuick.Controlsimport 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(); }
Rectangle { id: checkBoxBackground anchors { left: parent.left top: parent.top margins: 2 } width: childrenRect.width height: childrenRect.height color: "white" opacity: .75 radius: 5
ColumnLayout { spacing: 0 Row { CheckBox { id: openBox checked: true onCheckStateChanged: controlAnnotationSublayerVisibilityModel.openLayerVisible(); }
Text { id: openBoxText text: controlAnnotationSublayerVisibilityModel.openLayerText anchors.verticalCenter: openBox.verticalCenter color: scale.color } }
Row { CheckBox { id: closedBox checked: true onCheckStateChanged: controlAnnotationSublayerVisibilityModel.closedLayerVisible(); }
Text { id: closedBoxText text: controlAnnotationSublayerVisibilityModel.closedLayerText anchors.verticalCenter: closedBox.verticalCenter } } } }
Rectangle { id: currentScale anchors { bottom: view.attributionTop horizontalCenter: parent.horizontalCenter } width: childrenRect.width height: childrenRect.height
Text { id: scale text: "Current map scale: 1:%1".arg(Math.round(controlAnnotationSublayerVisibilityModel.mapScale)) color: controlAnnotationSublayerVisibilityModel.visibleAtCurrentExtent ? "black" : "grey" padding: 2 } } }
// Declare the C++ instance which creates the map etc. and supply the view ControlAnnotationSublayerVisibilitySample { id: controlAnnotationSublayerVisibilityModel mapView: view }}// [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 "ControlAnnotationSublayerVisibility.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("ControlAnnotationSublayerVisibility"));
// 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 ControlAnnotationSublayerVisibility::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/DisplayInformation/ControlAnnotationSublayerVisibility/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
ControlAnnotationSublayerVisibility { anchors.fill: parent }}