Display custom labels on a feature layer.

Use case
Labeling features is useful to visually display a key piece of information or attribute of a feature on a map. For example, you may want to label rivers or street with their names.
How to use the sample
Pan and zoom around the United States. Labels for congressional districts will be shown in red for Republican districts and blue for Democrat districts. Notice how labels pop into view as you zoom in.
How it works
To show custom labels on a feature layer:
- Create a
ServiceFeatureTableusing a feature service URL. - Create a
FeatureLayerfrom the service feature table. - Create an
ArcadeLabelExpressionfor the label definition.- You can use fields of the feature by using
$feature.field_namein the expression.
- You can use fields of the feature by using
- Create a
TextSymbolto control how the label text is styled. - Create a
LabelDefinitionby passing in theArcadeLabelExpressionandTextSymbol. - Add the definition to the feature layer with
featureLayer.labelDefinitions().append(labelDefinition). - Lastly, enable labels on the layer using
featureLayer.setLabelsEnabled().
Relevant API
- ArcadeLabelExpression
- FeatureLayer
- LabelDefinition
- TextSymbol
About the data
This sample uses the USA 116th Congressional Districts feature layer hosted on ArcGIS Online.
Additional information
Help regarding the Arcade label expression script for defining a label definition can be found on the ArcGIS Developers site.
Tags
attribute, deconfliction, label, labeling, string, symbol, text, visualization
Sample Code
// [WriteFile Name=ShowLabelsOnLayers, Category=DisplayInformation]// [Legal]// Copyright 2018 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 "ShowLabelsOnLayers.h"
// ArcGIS Maps SDK headers#include "ArcadeLabelExpression.h"#include "Envelope.h"#include "Error.h"#include "FeatureLayer.h"#include "LabelDefinition.h"#include "LabelDefinitionListModel.h"#include "LayerListModel.h"#include "Map.h"#include "MapQuickView.h"#include "MapTypes.h"#include "Point.h"#include "ServiceFeatureTable.h"#include "SpatialReference.h"#include "SymbolTypes.h"#include "TextSymbol.h"#include "Viewpoint.h"
// Qt headers#include <QFuture>
using namespace Esri::ArcGISRuntime;
ShowLabelsOnLayers::ShowLabelsOnLayers(QQuickItem* parent /* = nullptr */): QQuickItem(parent){}
void ShowLabelsOnLayers::init(){ // Register the map view for QML qmlRegisterType<MapQuickView>("Esri.Samples", 1, 0, "MapView"); qmlRegisterType<ShowLabelsOnLayers>("Esri.Samples", 1, 0, "ShowLabelsOnLayersSample");}
void ShowLabelsOnLayers::componentComplete(){ QQuickItem::componentComplete();
// find QML MapView component m_mapView = findChild<MapQuickView*>("mapView");
// Create a map using the light gray basemap m_map = new Map(BasemapStyle::ArcGISLightGray, this);
// Create a feature layer ServiceFeatureTable* featureTable = new ServiceFeatureTable(QUrl("https://services.arcgis.com/P3ePLMYs2RVChkJx/arcgis/rest/services/USA_116th_Congressional_Districts/FeatureServer/0"), this); FeatureLayer* featureLayer = new FeatureLayer(featureTable, this); connect(featureLayer, &FeatureLayer::doneLoading, this, [this, featureLayer](const Error& e) { if (!e.isEmpty()) return;
m_mapView->setViewpointAsync(Viewpoint(featureLayer->fullExtent().center(), 56759600)); }); m_map->operationalLayers()->append(featureLayer);
// Apply labels to the feature layer LabelDefinition* republicanLabelDef = createRepublicanLabelDefinition(); LabelDefinition* democratLabelDef = createDemocratLabelDefinition(); featureLayer->labelDefinitions()->append(republicanLabelDef); featureLayer->labelDefinitions()->append(democratLabelDef); featureLayer->setLabelsEnabled(true);
// Set map to map view m_mapView->setMap(m_map);}
LabelDefinition* ShowLabelsOnLayers::createRepublicanLabelDefinition(){ // This particular LabelDefinition will have the following characteristics: // (1) The 'ArcadeLabelExpression' defines that the label text displayed comes from the fields 'NAME', // the first letter of PARTY' (R or D), and 'CDFIPS' in the feature service in the format: // Firstname Lastname (R) // District # // (2) The 'TextSymbol' for the labeled text will be red with a white halo centered in the target polygon. // (3) The 'where' clause of the 'LabelDefinition' restricts the labels to data from Republican districts.
ArcadeLabelExpression* republicanArcadeLabelExpression = new ArcadeLabelExpression("$feature.NAME + ' (' + left($feature.PARTY,1) + ')\\nDistrict ' + $feature.CDFIPS", this);
TextSymbol* republicanTextSymbol = new TextSymbol(this); republicanTextSymbol->setSize(11); republicanTextSymbol->setColor(Qt::red); republicanTextSymbol->setHaloColor(Qt::white); republicanTextSymbol->setHaloWidth(2); republicanTextSymbol->setHorizontalAlignment(HorizontalAlignment::Center); republicanTextSymbol->setVerticalAlignment(VerticalAlignment::Middle);
LabelDefinition* republicanLabelDefinition = new LabelDefinition(republicanArcadeLabelExpression, republicanTextSymbol, this); republicanLabelDefinition->setWhereClause("PARTY = 'Republican'");
return republicanLabelDefinition;}
LabelDefinition* ShowLabelsOnLayers::createDemocratLabelDefinition(){ // This particular LabelDefinition will have the following characteristics: // (1) The 'ArcadeLabelExpression' defines that the label text displayed comes from the fields 'NAME', // the first letter of PARTY' (R or D), and 'CDFIPS' in the feature service in the format: // Firstname Lastname (D) // District # // (2) The 'TextSymbol' for the labeled text will be blue with a white halo centered in the target polygon. // (3) The 'where' clause of the 'LabelDefinition' restricts the labels to data from Democrat districts.
ArcadeLabelExpression* democratArcadeLabelExpression = new ArcadeLabelExpression("$feature.NAME + ' (' + left($feature.PARTY,1) + ')\\nDistrict ' + $feature.CDFIPS", this);
TextSymbol* democratTextSymbol = new TextSymbol(this); democratTextSymbol->setSize(11); democratTextSymbol->setColor(Qt::blue); democratTextSymbol->setHaloColor(Qt::white); democratTextSymbol->setHaloWidth(2); democratTextSymbol->setHorizontalAlignment(HorizontalAlignment::Center); democratTextSymbol->setVerticalAlignment(VerticalAlignment::Middle);
LabelDefinition* democratLabelDefinition = new LabelDefinition(democratArcadeLabelExpression, democratTextSymbol, this); democratLabelDefinition->setWhereClause("PARTY = 'Democrat'");
return democratLabelDefinition;}// [WriteFile Name=ShowLabelsOnLayers, Category=DisplayInformation]// [Legal]// Copyright 2018 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 SHOWLABELSONLAYERS_H#define SHOWLABELSONLAYERS_H
// Qt headers#include <QQuickItem>
namespace Esri::ArcGISRuntime{class Map;class MapQuickView;class LabelDefinition;}
class ShowLabelsOnLayers : public QQuickItem{ Q_OBJECT
public: explicit ShowLabelsOnLayers(QQuickItem* parent = nullptr); ~ShowLabelsOnLayers() override = default;
void componentComplete() override; static void init();
private: Esri::ArcGISRuntime::LabelDefinition* createRepublicanLabelDefinition(); Esri::ArcGISRuntime::LabelDefinition* createDemocratLabelDefinition();
Esri::ArcGISRuntime::Map* m_map = nullptr; Esri::ArcGISRuntime::MapQuickView* m_mapView = nullptr;};
#endif // SHOWLABELSONLAYERS_H// [WriteFile Name=ShowLabelsOnLayers, Category=DisplayInformation]// [Legal]// Copyright 2018 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 Esri.Samples
ShowLabelsOnLayersSample { id: rootRectangle clip: true width: 800 height: 600
// add a mapView component MapView { anchors.fill: parent objectName: "mapView"
Component.onCompleted: { // Set the focus on MapView to initially enable keyboard navigation forceActiveFocus(); } }}// [Legal]// Copyright 2018 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 "ShowLabelsOnLayers.h"
// ArcGIS Maps SDK headers#include "ArcGISRuntimeEnvironment.h"
// Qt headers#include <QCommandLineParser>#include <QDir>#include <QGuiApplication>#include <QQmlEngine>#include <QQuickView>
// 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("Show Labels on Layers"));
// 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 ShowLabelsOnLayers::init();
// Initialize application view QQuickView view; view.setResizeMode(QQuickView::SizeRootObjectToView);
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
// Add the import Path view.engine()->addImportPath(QDir(QCoreApplication::applicationDirPath()).filePath("qml")); // Add the Runtime and Extras path view.engine()->addImportPath(arcGISRuntimeImportPath);
// Set the source view.setSource(QUrl("qrc:/Samples/DisplayInformation/ShowLabelsOnLayers/ShowLabelsOnLayers.qml"));
view.show();
return app.exec();}