Apply a renderer to a sublayer.

Use case
A layer showing animal populations contains sublayers for different species. A renderer could be applied which gives each sublayer a different color, so that populations of each species can be compared visually.
How to use the sample
Wait for the map image layer to load. Click the ‘Change Sublayer Renderer’ button to apply a unique value renderer to see different population ranges in the counties sub-layer data.
How it works
- Create an
ArcGISMapImageLayerfrom its URL. - After it is done loading, get its
ArcGISSublayerListModelwithimageLayer::mapImageSublayers(). - Cast the sublayer you want to change to the appropriate type:
dynamic_cast<ArcGISMapImageSublayer>(ArcGISSublayer). - Create a
ClassBreaksRendererwith a collection ofClassBreaks for different population ranges. - Set the renderer of the sublayer with
sublayer::setRenderer(renderer).
Relevant API
- ArcGISMapImageLayer
- ArcGISMapImageSubLayer
- ClassBreaksRenderer
- ClassBreaksRenderer::classBreak
About the data
This application displays census data from an ArcGIS Server map service. It contains various population statistics, including total population for each county in 2007.
Additional information
The service hosting the layer must support dynamic layers to be able to change the rendering of sublayers.
Tags
class breaks, dynamic layer, dynamic rendering, renderer, sublayer, symbology, visualization
Sample Code
// [WriteFile Name=ChangeSublayerRenderer, Category=Layers]// [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 "ChangeSublayerRenderer.h"
// ArcGIS Maps SDK headers#include "ArcGISMapImageLayer.h"#include "ArcGISMapImageSublayer.h"#include "ArcGISSublayerListModel.h"#include "ClassBreaksRenderer.h"#include "Envelope.h"#include "Error.h"#include "LayerListModel.h"#include "Map.h"#include "MapQuickView.h"#include "MapTypes.h"#include "SimpleFillSymbol.h"#include "SimpleLineSymbol.h"#include "SpatialReference.h"#include "SymbolTypes.h"#include "Viewpoint.h"
using namespace Esri::ArcGISRuntime;
ChangeSublayerRenderer::ChangeSublayerRenderer(QQuickItem* parent /* = nullptr */): QQuickItem(parent){}
void ChangeSublayerRenderer::init(){ // Register the map view for QML qmlRegisterType<MapQuickView>("Esri.Samples", 1, 0, "MapView"); qmlRegisterType<ChangeSublayerRenderer>("Esri.Samples", 1, 0, "ChangeSublayerRendererSample");}
void ChangeSublayerRenderer::componentComplete(){ QQuickItem::componentComplete();
// find QML MapView component m_mapView = findChild<MapQuickView*>("mapView");
// Create a map using the streets basemap m_map = new Map(BasemapStyle::ArcGISStreets, this);
// Add the map image layer ArcGISMapImageLayer* mapImageLayer = new ArcGISMapImageLayer(QUrl("https://sampleserver6.arcgisonline.com/arcgis/rest/services/Census/MapServer"), this);
// Get the sublayer connect(mapImageLayer, &ArcGISMapImageLayer::doneLoading, this, [this, mapImageLayer](const Error& e) { if (!e.isEmpty()) return;
if (mapImageLayer->mapImageSublayers()->size() < 3) return;
m_sublayer = dynamic_cast<ArcGISMapImageSublayer*>(mapImageLayer->mapImageSublayers()->at(2));
// get the sublayer's original renderer connect(m_sublayer, &ArcGISMapImageSublayer::doneLoading, this, [this](const Error& e) { if (!e.isEmpty()) return;
m_originalRenderer = m_sublayer->renderer()->clone(this);
emit sublayerLoaded(); });
// load the sublayer m_sublayer->load(); });
// add the layer to the map m_map->operationalLayers()->append(mapImageLayer);
// set initial viewpoint Envelope env(-13834661.666904, 331181.323482, -8255704.998713, 9118038.075882, SpatialReference(3857)); Viewpoint initialViewpoint(env); m_map->setInitialViewpoint(initialViewpoint);
// create the class breaks renderer createClassBreaksRenderer();
// Set map to map view m_mapView->setMap(m_map);}
void ChangeSublayerRenderer::createClassBreaksRenderer(){ // create class breaks renderer m_classBreaksRenderer = new ClassBreaksRenderer(this); m_classBreaksRenderer->setFieldName(QStringLiteral("POP2007"));
// create and append class breaks m_classBreaksRenderer->classBreaks()->append(createClassBreak(QColor(227, 235, 207), -99, 8560)); m_classBreaksRenderer->classBreaks()->append(createClassBreak(QColor(150, 194, 191), 8560, 18109)); m_classBreaksRenderer->classBreaks()->append(createClassBreak(QColor(97, 166, 181), 18109, 35501)); m_classBreaksRenderer->classBreaks()->append(createClassBreak(QColor(69, 125, 150), 35501, 86100)); m_classBreaksRenderer->classBreaks()->append(createClassBreak(QColor(41, 84, 120), 86100, 10110975));}
// helper function to create class breaks for the rendererClassBreak* ChangeSublayerRenderer::createClassBreak(const QColor &color, double min, double max){ SimpleLineSymbol* outline = new SimpleLineSymbol(SimpleLineSymbolStyle::Solid, QColor(153, 153, 153), 1.0f /*width*/, this); SimpleFillSymbol* sfs1 = new SimpleFillSymbol(SimpleFillSymbolStyle::Solid, color, outline, this); const QString description = QString("> %1 to %2").arg(QString::number(min), QString::number(max)); const QString label = description; return new ClassBreak(description, label, min, max, sfs1);}
// apply the class breaks renderervoid ChangeSublayerRenderer::applyRenderer(){ if (!m_sublayer || !m_classBreaksRenderer) return;
m_sublayer->setRenderer(m_classBreaksRenderer);}
// reset to the original renderervoid ChangeSublayerRenderer::resetRenderer(){ if (!m_sublayer || !m_originalRenderer) return;
m_sublayer->setRenderer(m_originalRenderer);}// [WriteFile Name=ChangeSublayerRenderer, Category=Layers]// [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 CHANGESUBLAYERRENDERER_H#define CHANGESUBLAYERRENDERER_H
// Qt headers#include <QQuickItem>
namespace Esri::ArcGISRuntime{class Map;class MapQuickView;class Renderer;class ClassBreaksRenderer;class ArcGISMapImageSublayer;class ClassBreak;}
class ChangeSublayerRenderer : public QQuickItem{ Q_OBJECT
public: explicit ChangeSublayerRenderer(QQuickItem* parent = nullptr); ~ChangeSublayerRenderer() override = default;
void componentComplete() override; static void init(); Q_INVOKABLE void applyRenderer(); Q_INVOKABLE void resetRenderer();
signals: void sublayerLoaded();
private: Esri::ArcGISRuntime::Map* m_map = nullptr; Esri::ArcGISRuntime::MapQuickView* m_mapView = nullptr; Esri::ArcGISRuntime::Renderer* m_originalRenderer = nullptr; Esri::ArcGISRuntime::ClassBreaksRenderer* m_classBreaksRenderer = nullptr; Esri::ArcGISRuntime::ArcGISMapImageSublayer* m_sublayer = nullptr; void createClassBreaksRenderer(); Esri::ArcGISRuntime::ClassBreak* createClassBreak(const QColor& color, double min, double max);};
#endif // CHANGESUBLAYERRENDERER_H// [WriteFile Name=ChangeSublayerRenderer, Category=Layers]// [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.Windowimport QtQuick.Controlsimport Esri.Samples
ChangeSublayerRendererSample { 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(); } }
onSublayerLoaded: { applyRendererButton.enabled = true; resetRendererButton.enabled = true; }
Column { anchors { left: parent.left top: parent.top margins: 5 } spacing: 5
Button { id: applyRendererButton width: 200 enabled: false text: "Apply Renderer" onClicked: applyRenderer(); }
Button { id: resetRendererButton width: 200 enabled: false text: "Reset" onClicked: resetRenderer(); } }}// [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 "ChangeSublayerRenderer.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("ChangeSublayerRenderer"));
// 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 ChangeSublayerRenderer::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/Layers/ChangeSublayerRenderer/ChangeSublayerRenderer.qml"));
view.show();
return app.exec();}