Perform map navigation and identify nearby features using only the keyboard.

Use case
Keyboard access is an important part of building inclusive GIS applications. Users who cannot or prefer not to use touch or pointer input need a way to move around the map, discover features, and read feature details from the keyboard.
How to use the sample
Use keyboard navigation to pan and zoom until restaurants appear inside the rectangle. Restaurants inside the rectangle are selected and labeled in reading order, from top-to-bottom and left-to-right.
Press number keys 1 through 9 to show details for the matching restaurant. Press Esc to dismiss the callout and show the selection rectangle again.
If more than nine restaurants are inside the rectangle, zoom in or pan to narrow the results.
How it works
- Create a
Mapwith anarcGISLightGraybasemap centered on Redlands. - Create a
ServiceFeatureTablefrom the Redlands restaurants feature service. - Create a
FeatureLayerfrom the service feature table and apply aSimpleRendererwith a circular marker symbol. - Display the map and a
GraphicsOverlayin aMapView. - Use
MapViewReaderto convert the four corners of the centered screen-space rectangle to map locations and create a map-spacePolygon. - Query the restaurant feature table with
QueryParametersusing the polygon and an intersects spatial relationship. - Sort queried point features north-to-south, then west-to-east, so labels match reading order when the map is north-up.
- Select the queried features on the
FeatureLayer. - Add numbered
TextSymbolgraphics for the current group of features to the graphics overlay. - Add hidden SwiftUI
Buttons with.keyboardShortcutmodifiers for number keys1through9. Each shortcut shows aCalloutfor the corresponding numbered feature, while the map view provides built-inEschandling to dismiss the callout.
Relevant API
- FeatureLayer
- Graphic
- GraphicsOverlay
- Map
- MapView
- Polygon
About the data
This sample uses a Redlands restaurants feature layer covering food establishments in Redlands, California. Each feature represents a single restaurant.
Additional information
The map view supports built-in keyboard shortcuts such as arrow keys to pan and + and - to zoom. See Navigate a map view for the complete list of built-in interactions.
When Full Keyboard Access is enabled, the system may reserve the plain arrow keys for moving focus. In that mode, use Shift + arrow keys to pan the map while keeping the built-in Alt/Option + arrow shortcuts available for rotation and reset north.
Tags
accessibility, accessible, identify, inclusive, keyboard, navigation, selection, WCAG
Sample code
// 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//// https://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 ArcGISimport SwiftUIimport TipKit
struct NavigateMapViewAndIdentifyFeaturesWithKeyboardView: View { /// Opens URLs using SwiftUI's environment-provided action. @Environment(\.openURL) private var openURL
/// The view model for the sample. @State private var model = Model()
/// The map displayed in the map view. @State private var map: Map = { let map = Map(basemapStyle: .arcGISLightGray) map.initialViewpoint = Viewpoint( center: Point( x: -117.1825, y: 34.0556, spatialReference: .wgs84 ), scale: 4_000 ) return map }()
/// The size of the map view. @State private var mapSize: CGSize = .zero
/// The error shown in the error alert. @State private var error: (any Error)?
/// A Boolean value indicating whether the initial draw has completed. @State private var initialDrawCompleted = false
/// The placement of the restaurant details callout. @State private var calloutPlacement: CalloutPlacement?
/// The feature shown in the callout. @State private var calloutFeature: Feature?
/// The status message shown when a number key has no matching restaurant. @State private var statusMessage = ""
/// The side length of the centered area-of-interest rectangle, in screen points. private var selectionRectangleLength: CGFloat { 360 }
/// The selection halo color for selected restaurant features. private static let selectionHaloColor = Color( red: 190 / 255, green: 24 / 255, blue: 93 / 255 )
/// A Boolean value indicating whether the map view is currently navigating. @State private var isNavigating = false
private var isFullKeyboardAccessEnabled: Bool { guard let window = UIApplication.shared.connectedScenes .compactMap({ ($0 as? UIWindowScene)?.keyWindow }) .first else { return false } // On iPhone, a focus system exists only when Full Keyboard Access is on. // Caveat: on iPad, a connected hardware keyboard alone creates a focus // system, so this reads as a false positive there. return UIFocusSystem.focusSystem(for: window) != nil }
var body: some View { MapViewReader { mapView in MapView(map: map, graphicsOverlays: [model.labelOverlay]) .selectionColor(Self.selectionHaloColor) .callout(placement: $calloutPlacement.animation(.default.speed(2))) { _ in if let calloutFeature { calloutContent(for: calloutFeature) } } .onNavigatingChanged { newIsNavigating in isNavigating = newIsNavigating } .onDrawStatusChanged { newDrawStatus in guard newDrawStatus == .completed, !initialDrawCompleted else { return } initialDrawCompleted = true } .task(id: initialDrawCompleted) { guard initialDrawCompleted else { return } // Give the map view proxy time to settle before the first query. try? await Task.sleep(for: .milliseconds(500)) await refreshSelection(mapSize: mapSize, mapView: mapView) } .task(id: isNavigating) { if isNavigating { await dismissCallout() } else if initialDrawCompleted { await refreshSelection( mapSize: mapSize, mapView: mapView ) } } .overlay(alignment: .center) { if calloutPlacement == nil { let rectangleLength = self.rectangleLength(for: mapSize) RoundedRectangle(cornerRadius: 4) .fill(.pink.opacity(0.08)) .overlay( RoundedRectangle(cornerRadius: 4) .stroke(.pink, lineWidth: 2) ) .frame(width: rectangleLength, height: rectangleLength) .allowsHitTesting(false) .accessibilityHidden(true) } } .overlay(alignment: .top) { TipView(AreaOfInterestTip()) } .overlay(alignment: .bottomTrailing) { if !isFullKeyboardAccessEnabled { TipView(EnableKeyboardAccessTip()) { _ in openAccessibilitySettings() } } } .overlay(alignment: .bottom) { VStack(spacing: 8) { ZStack { ForEach(1...9, id: \.self) { number in Button("Select restaurant \(number)") { showCallout(forFeatureAtIndex: number - 1) } .keyboardShortcut( KeyEquivalent(Character(String(number))), modifiers: [] ) }
Button("Dismiss callout") { Task { await dismissCallout() } } .keyboardShortcut(.escape, modifiers: []) } .frame(width: 0, height: 0) .opacity(0) .allowsHitTesting(false) .accessibilityHidden(true)
if model.hasMoreThanNineSelectedFeatures { Text("More than 9 restaurants are in the search area. Zoom in or pan to narrow the results.") .statusText() }
if !statusMessage.isEmpty { Text(statusMessage) .statusText() } } .padding(.bottom, 10) } .onAppear { // TipKit configuration is intended to happen once per process. try? Tips.configure([.displayFrequency(.immediate)])
guard map.operationalLayers.isEmpty else { return } map.addOperationalLayer(model.restaurantsLayer) } .errorAlert(presentingError: $error) } .onGeometryChange(for: CGSize.self, of: \.size) { newMapSize in mapSize = newMapSize } }
/// The selection rectangle's side length, clamped to fit within the map. private func rectangleLength(for mapSize: CGSize) -> CGFloat { min(selectionRectangleLength, mapSize.width, mapSize.height) }
/// Refreshes the selected and numbered restaurant features for the current rectangle. private func refreshSelection(mapSize: CGSize, mapView: MapViewProxy) async { if let polygon = makeSelectionPolygon(mapSize: mapSize, mapView: mapView) { do { try await model.selectFeatures( in: polygon, pointConverter: mapView.screenPoint(fromLocation:) ) } catch { self.error = error } } else { model.clearSelection() } }
/// Makes a polygon matching the centered selection rectangle's map footprint. private func makeSelectionPolygon(mapSize: CGSize, mapView: MapViewProxy) -> ArcGIS.Polygon? { let halfLength = rectangleLength(for: mapSize) / 2 let center = CGPoint(x: mapSize.width / 2, y: mapSize.height / 2) let screenCorners = [ CGPoint(x: center.x - halfLength, y: center.y - halfLength), CGPoint(x: center.x + halfLength, y: center.y - halfLength), CGPoint(x: center.x + halfLength, y: center.y + halfLength), CGPoint(x: center.x - halfLength, y: center.y + halfLength) ] let mapCorners = screenCorners.compactMap(mapView.location(fromScreenPoint:)) guard mapCorners.count == screenCorners.count else { return nil }
return ArcGIS.Polygon(points: mapCorners) }
/// Shows the details callout for the selected numbered feature. private func showCallout(forFeatureAtIndex index: Int) { if model.numberedFeatures.indices.contains(index), let anchor = model.numberedFeatures[index].geometry as? Point { let feature = model.numberedFeatures[index] statusMessage = "" calloutFeature = feature calloutPlacement = .geoElement(feature, tapLocation: anchor) } else { statusMessage = "No restaurant is assigned to \(index + 1)." calloutFeature = nil calloutPlacement = nil } }
/// Dismisses the details callout and restores the selection rectangle. private func dismissCallout() async { calloutFeature = nil calloutPlacement = nil statusMessage = "" }
/// The callout content for a restaurant feature. private func calloutContent(for feature: Feature) -> some View { let anchor = feature.geometry as? Point let wgs84Point = anchor.flatMap { GeometryEngine.project($0, into: .wgs84) }
return VStack(alignment: .leading) { Text(model.name(for: feature) ?? "Restaurant") .font(.headline) if let wgs84Point { Text("Lat: \(wgs84Point.y, format: .number.precision(.fractionLength(6)))") Text("Lon: \(wgs84Point.x, format: .number.precision(.fractionLength(6)))") } } .padding(5) }
/// Opens the main Accessibility menu in Settings. private func openAccessibilitySettings() {#if targetEnvironment(macCatalyst) openURL(.macOSAccessibilitySettings)#else openURL(.accessibilitySettings)#endif }}
private extension View { /// Styles a status message to float above the map. func statusText() -> some View { self .font(.footnote) .multilineTextAlignment(.center) .padding(8) .background(.regularMaterial) .clipShape(.rect(cornerRadius: 8)) }}
private extension URL {#if !targetEnvironment(macCatalyst) /// The URL of the Accessibility menu in the Settings app. static var accessibilitySettings: URL { URL(string: "App-prefs:ACCESSIBILITY")! }#else /// The URL of the Accessibility pane in the macOS System Settings app. static var macOSAccessibilitySettings: URL { URL(string: "x-apple.systempreferences:com.apple.Accessibility-Settings.extension")! }#endif}
#Preview { NavigationStack { NavigateMapViewAndIdentifyFeaturesWithKeyboardView() }}// 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//// https://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 ArcGISimport Foundationimport UIKit
extension NavigateMapViewAndIdentifyFeaturesWithKeyboardView { /// The model for the sample. @MainActor @Observable final class Model { /// Attribute used to title and label each feature. private static let nameAttribute = "name"
/// The fill color used for restaurant marker symbols. private static let markerFillColor = UIColor( red: 11 / 255, green: 79 / 255, blue: 138 / 255, alpha: 1 )
/// The text color used for numbered restaurant labels. private static let labelTextColor = UIColor( red: 31 / 255, green: 35 / 255, blue: 40 / 255, alpha: 1 )
/// The feature table of restaurants in Redlands. private let restaurantsTable = ServiceFeatureTable(url: .redlandsRestaurants)
/// The feature layer holding the restaurants displayed and identified by the sample. let restaurantsLayer: FeatureLayer
/// The overlay for the numbered 1-9 labels. let labelOverlay = GraphicsOverlay()
/// Features currently in the area of interest, indexed by the matching number key. private(set) var numberedFeatures: [Feature] = []
/// A Boolean value indicating whether more than nine features are selected. private(set) var hasMoreThanNineSelectedFeatures = false
init() { let restaurantSymbol = SimpleMarkerSymbol( style: .circle, color: Self.markerFillColor, size: 12 ) restaurantSymbol.outline = SimpleLineSymbol( style: .solid, color: .white, width: 1.5 )
restaurantsLayer = FeatureLayer(featureTable: restaurantsTable) restaurantsLayer.renderer = SimpleRenderer(symbol: restaurantSymbol) }
/// Selects, numbers, and labels restaurant features that intersect a given polygon. /// - Parameters: /// - polygon: The polygon used to query restaurant features. /// - pointConverter: A closure that converts a map location to a screen point. func selectFeatures(in polygon: ArcGIS.Polygon, pointConverter: (Point) -> CGPoint?) async throws { if restaurantsTable.loadStatus != .loaded { try await restaurantsTable.load() }
clearSelection()
let orderedFeatures = try await makeOrderedFeatures( selection: polygon, pointConverter: pointConverter )
hasMoreThanNineSelectedFeatures = orderedFeatures.count > .maximumNumberedFeatures
// Only select the numbered features (first 9). let numberedOrderedFeatures = orderedFeatures.lazy .map(\.feature) .prefix(.maximumNumberedFeatures) restaurantsLayer.selectFeatures(numberedOrderedFeatures)
addNumberedLabels(for: orderedFeatures) }
/// Clears selected features, label graphics, and numbered feature state. func clearSelection() { restaurantsLayer.clearSelection() labelOverlay.removeAllGraphics() numberedFeatures.removeAll() hasMoreThanNineSelectedFeatures = false }
/// Reads the feature's name attribute. /// - Parameter feature: The feature whose name is read. /// - Returns: The feature's name, or `nil` if no name exists. func name(for feature: Feature) -> String? { guard let name = feature.attributes[Self.nameAttribute] as? String else { return nil }
let trimmedName = name.trimmingCharacters(in: .whitespacesAndNewlines)
guard !trimmedName.isEmpty else { return nil }
return trimmedName }
/// Queries and sorts restaurant features from top-to-bottom, then left-to-right in screen space. /// - Parameters: /// - selection: The polygon used to query restaurant features. /// - pointConverter: A closure that converts a map location to a screen point. /// - Returns: The ordered restaurant features with their map and screen positions. private func makeOrderedFeatures(selection: ArcGIS.Polygon, pointConverter: (Point) -> CGPoint?) async throws -> [OrderedFeature] { let queryParameters = QueryParameters() queryParameters.geometry = selection queryParameters.spatialRelationship = .intersects queryParameters.maxFeatures = 1000
let queryResult = try await restaurantsTable.queryFeatures(using: queryParameters)
return withoutActuallyEscaping(pointConverter) { escapablePointConverter in queryResult .features() .lazy .compactMap { feature in guard let anchor = feature.geometry as? Point, let screenPoint = escapablePointConverter(anchor) else { return nil } return OrderedFeature(feature: feature, anchor: anchor, screenPoint: screenPoint) } .sorted { lhs, rhs in // Sort by visual reading order: top-to-bottom, then // left-to-right. return if lhs.screenPoint.y != rhs.screenPoint.y { lhs.screenPoint.y < rhs.screenPoint.y } else { lhs.screenPoint.x < rhs.screenPoint.x } } } }
/// Adds numbered text labels for the first restaurant features. /// - Parameter orderedFeatures: The ordered restaurant features to label. private func addNumberedLabels(for orderedFeatures: [OrderedFeature]) { let numberedOrderedFeatures = orderedFeatures.prefix(.maximumNumberedFeatures)
for (offset, orderedFeature) in numberedOrderedFeatures.enumerated() { let number = offset + 1 let text = name(for: orderedFeature.feature).map { "\(number): \($0)" } ?? "\(number)" let labelSymbol = TextSymbol( text: text, color: Self.labelTextColor, size: 15, horizontalAlignment: .center, verticalAlignment: .top ) labelSymbol.haloColor = .white labelSymbol.haloWidth = 2 labelSymbol.offsetY = -14 labelOverlay.addGraphic( Graphic(geometry: orderedFeature.anchor, symbol: labelSymbol) ) numberedFeatures.append(orderedFeature.feature) } }
/// A feature and its map and screen locations. private struct OrderedFeature { let feature: Feature let anchor: Point let screenPoint: CGPoint } }}
private extension Int { /// The maximum number of features that can be identified with number keys. static let maximumNumberedFeatures = 9}
private extension URL { /// The URL of the Redlands restaurants feature service. static var redlandsRestaurants: URL { URL(string: "https://services2.arcgis.com/ZQgQTuoyBrtmoGdP/arcgis/rest/services/redlands_food/FeatureServer/0")! }}// 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//// https://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 SwiftUIimport TipKit
extension NavigateMapViewAndIdentifyFeaturesWithKeyboardView { /// A TipKit tip that explains the centered rectangle. struct AreaOfInterestTip: Tip { var title: Text { Text("Use the rectangle as the search area") }
var message: Text? { Text( """ Use the arrow keys ← → ↑ ↓ to focus the map. When Full \ Keyboard Access is enabled, use Shift + arrow keys instead. Pan \ until the restaurants you want to inspect are inside the rectangle.
Press 1–9 to select a highlighted restaurant and view its details. """ ) }
var image: Image? { Image(systemName: "rectangle.dashed") } }
struct EnableKeyboardAccessTip: Tip { /// The ID of the action that opens the Settings app. static let openSettingsActionID = "openSettings"
var title: Text { Text("Enable Full Keyboard Access") }
var message: Text? { Text( """ To use a hardware keyboard with your mobile device you need to \ enable Full Keyboard Access. You can do this by opening the \ Settings app and navigating to:
Accessibility > Keyboards & Typing. """ ) }
var image: Image? { Image(systemName: "keyboard") }
var actions: [Action] { Action( id: Self.openSettingsActionID, title: "Open Accessibility Settings" ) } }}