Determine if a layer is currently being viewed.

Use case
The view status includes information on the loading state of layers and whether layers are visible at a given scale. You might change how a layer is displayed in a layer list to communicate whether it is being viewed in the map. For example, you could show a loading spinner next to its name when the view status is Loading, grey out the name when NotVisible or OutOfScale, show the name normally when Active, or with a warning or error icon when the status is Warning or Error.
How to use the sample
Tap the Load layer button to add a feature layer to the map. The current view status of the layer will display on the map. Zoom in and out of the map and note the layer disappears when the map is scaled outside of its min and max scale range. Control the layer’s visibility with the Hide layer button. If you disconnect your device from the network and pan around the map, a warning will display. Reconnect to the network to remove the warning. The layer’s current view status will update accordingly as you carry out these actions.
How it works
- Create a
Mapwith some operational layers. - Set the map on a
MapView. - Connect to the
layerViewStateChangedsignal from the map view. - Display the
LayerViewStatusflag for theFeatureLayer.
Relevant API
- LayerViewState
- LayerViewStatus
- Map
- MapQuickView::layerViewStateChanged
- MapView
About the data
The Satellite (MODIS) Thermal Hotspots and Fire Activity layer presents detectable thermal activity from MODIS satellites for the last 48 hours. MODIS Global Fires is a product of NASA’s Earth Observing System Data and Information System (EOSDIS), part of NASA’s Earth Science Data. EOSDIS integrates remote sensing and GIS technologies to deliver global MODIS hotspot/fire locations to natural resource managers and other stakeholders around the World.
Additional information
The following are members of the LayerViewStatus enum:
LayerViewStatus::Active: The layer in the view is active.LayerViewStatus::NotVisible: The layer in the view is not visible.LayerViewStatus::OutOfScale: The layer in the view is out of scale. A status ofLayerViewStatus::OutOfScaleindicates that the view is zoomed outside of the scale range of the layer. If the view is zoomed too far in (e.g. to a street level), it is beyond the max scale defined for the layer. If the view has zoomed too far out (e.g. to global scale), it is beyond the min scale defined for the layer.LayerViewStatus::Loading: The layer in the view is loading. Once loading has completed, the layer will be available for display in the view. If there was a problem loading the layer, the status will be set to ERROR.LayerViewStatus::Error: The layer in the view has an unrecoverable error. When the status isLayerViewStatus::Error, the layer cannot be rendered in the view. For example, it may have failed to load, be an unsupported layer type, or contain invalid data.LayerViewStatus::Warning: The layer in the view has a non-breaking problem with its display, such as incomplete information (eg. by requesting more features than the max feature count of a service) or a network request failure.
If your device supports airplane mode, you can toggle this on and pan around the map to see layers display the WARNING status when they cannot online fetch data. Toggle airplane mode back off to see the warning disappear.
Tags
layer, load, map, status, view, visibility
Sample Code
// [WriteFile Name=DisplayLayerViewDrawState, Category=Maps]// [Legal]// Copyright 2020 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 "DisplayLayerViewDrawState.h"
// ArcGIS Maps SDK headers#include "Error.h"#include "FeatureLayer.h"#include "LayerListModel.h"#include "LayerViewState.h"#include "Map.h"#include "MapQuickView.h"#include "MapTypes.h"#include "Point.h"#include "Portal.h"#include "PortalItem.h"#include "SpatialReference.h"#include "Viewpoint.h"
// Qt headers#include <QFuture>
using namespace Esri::ArcGISRuntime;
DisplayLayerViewDrawState::DisplayLayerViewDrawState(QObject* parent /* = nullptr */) : QObject(parent), m_map(new Map(BasemapStyle::ArcGISTopographic, this)){}
DisplayLayerViewDrawState::~DisplayLayerViewDrawState() = default;
void DisplayLayerViewDrawState::init(){ // Register the map view for QML qmlRegisterType<MapQuickView>("Esri.Samples", 1, 0, "MapView"); qmlRegisterType<DisplayLayerViewDrawState>("Esri.Samples", 1, 0, "DisplayLayerViewDrawStateSample");}
MapQuickView* DisplayLayerViewDrawState::mapView() const{ return m_mapView;}
// Set the view (created in QML)void DisplayLayerViewDrawState::setMapView(MapQuickView* mapView){ if (!mapView || mapView == m_mapView) { return; }
m_mapView = mapView; m_mapView->setMap(m_map);
connect(m_mapView, &MapQuickView::layerViewStateChanged, this, &DisplayLayerViewDrawState::onLayerViewStateCompleted);
emit mapViewChanged();}
void DisplayLayerViewDrawState::loadLayer(){ // load a feature layer from a portal item Portal* portal = new Portal(this); m_portalItem = new PortalItem(portal, "b8f4033069f141729ffb298b7418b653", this); m_featureLayer = new FeatureLayer(m_portalItem, 0, this);
connect(m_featureLayer, &FeatureLayer::loadStatusChanged, this, [this](LoadStatus loadStatus) { m_loading = (loadStatus == LoadStatus::Loading) ? true : false; emit loadingChanged(); });
// load feature layer and set the viewpoint connect(m_featureLayer, &FeatureLayer::doneLoading, this, [this](const Error& e) { if (!e.isEmpty()) { return; }
const Point point{-11000000, 4500000, SpatialReference::webMercator()}; const Viewpoint vp{point, 40000000.0}; m_mapView->setViewpointAsync(vp); });
// set min/max scale to demonstrate different view states. m_featureLayer->setMinScale(400000000.0); m_featureLayer->setMaxScale(400000000.0 / 10); m_map->operationalLayers()->append(m_featureLayer);}
void DisplayLayerViewDrawState::changeFeatureLayerVisibility(bool visible){ if (m_featureLayer->loadStatus() == LoadStatus::Loaded) { m_featureLayer->setVisible(visible); }}
void DisplayLayerViewDrawState::onLayerViewStateCompleted(Layer* layer, LayerViewState layerViewState){ // check if feature layer has been created otherwise do nothing. if (!m_featureLayer) { return; }
// only update the QStringList if the layer is the feature layer. if (layer->name() != m_featureLayer->name()) { return; }
// clear string list for new view state(s). m_viewStatuses.clear();
if (layerViewState.statusFlags() & Esri::ArcGISRuntime::LayerViewStatus::Active) { m_viewStatuses.append("Active"); } if (layerViewState.statusFlags() & Esri::ArcGISRuntime::LayerViewStatus::NotVisible) { m_viewStatuses.append("NotVisible"); } if (layerViewState.statusFlags() & Esri::ArcGISRuntime::LayerViewStatus::OutOfScale) { m_viewStatuses.append("OutOfScale"); } if (layerViewState.statusFlags() & Esri::ArcGISRuntime::LayerViewStatus::Loading) { m_viewStatuses.append("Loading"); } if (layerViewState.statusFlags() & Esri::ArcGISRuntime::LayerViewStatus::Error) { m_viewStatuses.append("Error"); } if (layerViewState.statusFlags() & Esri::ArcGISRuntime::LayerViewStatus::Warning) { m_viewStatuses.append("Warning"); if (!layerViewState.error().isEmpty()) { const QString warningMessage = QString("Warning message: %1").arg(layerViewState.error().message()); m_warningMessage = warningMessage; emit warningMessageChanged(); } } emit viewStatusChanged();}// [WriteFile Name=DisplayLayerViewDrawState, Category=Maps]// [Legal]// Copyright 2020 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 DISPLAYLAYERVIEWDRAWSTATE_H#define DISPLAYLAYERVIEWDRAWSTATE_H
// Qt headers#include <QObject>
namespace Esri::ArcGISRuntime{ class FeatureLayer; class Map; class MapQuickView; class PortalItem; class Layer; class LayerViewState;} // namespace Esri::ArcGISRuntime
Q_MOC_INCLUDE("MapQuickView.h")
class DisplayLayerViewDrawState : public QObject{ Q_OBJECT
Q_PROPERTY(Esri::ArcGISRuntime::MapQuickView* mapView READ mapView WRITE setMapView NOTIFY mapViewChanged) Q_PROPERTY(QStringList viewStatus MEMBER m_viewStatuses NOTIFY viewStatusChanged) Q_PROPERTY(QString warningMessage MEMBER m_warningMessage NOTIFY warningMessageChanged) Q_PROPERTY(bool loading MEMBER m_loading NOTIFY loadingChanged)
public: explicit DisplayLayerViewDrawState(QObject* parent = nullptr); ~DisplayLayerViewDrawState();
static void init(); void onLayerViewStateCompleted(Esri::ArcGISRuntime::Layer* layer, Esri::ArcGISRuntime::LayerViewState layerViewState);
Q_INVOKABLE void loadLayer(); Q_INVOKABLE void changeFeatureLayerVisibility(bool visible);
signals: void mapViewChanged(); void viewStatusChanged(); void loadingChanged(); void warningMessageChanged();
private: Esri::ArcGISRuntime::MapQuickView* mapView() const; void setMapView(Esri::ArcGISRuntime::MapQuickView* mapView);
Esri::ArcGISRuntime::Map* m_map = nullptr; Esri::ArcGISRuntime::MapQuickView* m_mapView = nullptr; Esri::ArcGISRuntime::FeatureLayer* m_featureLayer = nullptr; Esri::ArcGISRuntime::PortalItem* m_portalItem = nullptr;
bool m_loading = false; QStringList m_viewStatuses; QString m_warningMessage;};
#endif // DISPLAYLAYERVIEWDRAWSTATE_H// [WriteFile Name=DisplayLayerViewDrawState, Category=Maps]// [Legal]// Copyright 2020 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.Samplesimport Esri.ArcGISRuntime.Toolkit
Item {
// add a mapView component MapView { id: view anchors.fill: parent
Component.onCompleted: { // Set the focus on MapView to initially enable keyboard navigation forceActiveFocus(); }
Dialog { id: warningDialog anchors.centerIn: parent standardButtons: Dialog.Ok visible: model.warningMessage !== "" ? true : false Text { text: model.warningMessage; } }
Rectangle { id: controlRect anchors { bottom: loadLayerButton.top horizontalCenter: parent.horizontalCenter margins: 5 } width: controlLayout.implicitWidth + 4 height: controlLayout.implicitHeight + 4 color: palette.base radius: 3
MouseArea { anchors.fill: controlLayout acceptedButtons: Qt.LeftButton | Qt.RightButton onClicked: mouse => mouse.accepted = true onDoubleClicked: mouse => mouse.accepted = true onWheel: wheel => wheel.accepted = true }
ColumnLayout{ id: controlLayout anchors.centerIn: parent
Label { id: textHeader text: qsTr("Current view status:") Layout.alignment: Qt.AlignHCenter }
Column { id: column Layout.alignment: Qt.AlignHCenter Repeater { id: layerViewStatusRepeater model: model.viewStatus Layout.alignment: Qt.AlignHCenter Item { width: childrenRect.width height: childrenRect.height Label { text: modelData } } } } } }
Button { id: loadLayerButton anchors { bottom: view.attributionTop horizontalCenter: parent.horizontalCenter margins: 5 } text: qsTr("Load Layer") enabled: !model.loading clip: true onClicked: { if (text === qsTr("Load Layer")) { model.loadLayer(); text = qsTr("Hide Layer"); } else if (text === qsTr("Hide Layer")) { text = qsTr("Show Layer"); model.changeFeatureLayerVisibility(false);
} else if (text === qsTr("Show Layer")) { text = qsTr("Hide Layer"); model.changeFeatureLayerVisibility(true); } } } }
// Declare the C++ instance which creates the map etc. and supply the view DisplayLayerViewDrawStateSample { id: model mapView: view }}// [WriteFile Name=DisplayLayerViewDrawState, Category=Maps]// [Legal]// Copyright 2020 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 "DisplayLayerViewDrawState.h"
// ArcGIS Maps SDK headers#include "ArcGISRuntimeEnvironment.h"
// Qt headers#include <QDir>#include <QGuiApplication>#include <QQmlApplicationEngine>
// Other headers#include "Esri/ArcGISRuntime/Toolkit/register.h"
// Platform specific headers#ifdef Q_OS_WIN#include <Windows.h>#endif
int main(int argc, char* argv[]){ QGuiApplication app(argc, argv); app.setApplicationName(QString("DisplayLayerViewDrawState"));
// 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 DisplayLayerViewDrawState::init();
// Initialize application view QQmlApplicationEngine engine; // Add the import Path engine.addImportPath(QDir(QCoreApplication::applicationDirPath()).filePath("qml"));
#ifdef ARCGIS_RUNTIME_IMPORT_PATH_2 engine.addImportPath(ARCGIS_RUNTIME_IMPORT_PATH_2);#endif
Esri::ArcGISRuntime::Toolkit::registerComponents(engine);
// Set the source engine.load(QUrl("qrc:/Samples/Maps/DisplayLayerViewDrawState/main.qml"));
return app.exec();}// Copyright 2020 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.
import QtQuick.Controlsimport Esri.Samples
ApplicationWindow { visible: true width: 800 height: 600
DisplayLayerViewDrawState { anchors.fill: parent }}