Geocode offline

View on GitHub

Geocode addresses to locations and reverse geocode locations to addresses offline.

Image of geocode offline

Use case

You can use an address locator file to geocode addresses and locations. For example, you could provide offline geocoding capabilities to field workers repairing critical infrastructure in a disaster when network availability is limited.

How to use the sample

Type the address in the search bar or tap the arrow button in the toolbar and select from the list to geocode the address and view the result on the map. Tap a location to create a pin and reverse geocode. Tap, hold and pan to get real-time geocoding.

How it works

  1. Use the path of a .loc file to create a LocatorTask object.
  2. Set up GeocodeParameters and call LocatorTask.geocode(forSearchText:using:) to get geocode results.

Relevant API

  • GeocodeParameters
  • GeocodeResult
  • LocatorTask
  • ReverseGeocodeParameters

Offline data

The sample viewer will download offline data automatically before loading the sample.

Tags

geocode, geocoder, locator, offline, package, query, search

Sample Code

GeocodeOfflineView.swiftGeocodeOfflineView.swiftGeocodeOfflineView.Model.swift
Use dark colors for code blocksCopy
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
// Copyright 2023 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 ArcGIS
import SwiftUI

struct GeocodeOfflineView: View {
    /// The view model for the sample.
    @StateObject private var model = Model()

    /// The viewpoint of the map view, initially centered on San Diego, CA, USA.
    @State private var viewpoint = Viewpoint(
        center: Point(x: -13_042_250, y: 3_857_970, spatialReference: .webMercator),
        scale: 2e4
    )

    /// The text in the search bar.
    @State private var searchText = ""

    /// The search text that has been submitted.
    @State private var submittedSearchText: String?

    /// A Boolean value indicating whether the "No results found." alert is showing.
    @State private var resultAlertIsShowing = false

    /// A pre-populated list of example addresses.
    private let exampleAddresses = [
        "910 N Harbor Dr, San Diego, CA 92101",
        "2920 Zoo Dr, San Diego, CA 92101",
        "111 W Harbor Dr, San Diego, CA 92101",
        "868 4th Ave, San Diego, CA 92101",
        "750 A St, San Diego, CA 92101"
    ]

    var body: some View {
        GeocodeMapView(model: model, viewpoint: $viewpoint)
            .searchable(text: $searchText, prompt: "Type in an address")
            .autocorrectionDisabled()
            .onSubmit(of: .search) {
                submittedSearchText = searchText
            }
            .toolbar {
                ToolbarItem(placement: .primaryAction) {
                    Menu {
                        ForEach(exampleAddresses, id: \.self) { address in
                            Button(address) {
                                searchText = address
                                submittedSearchText = address
                            }
                        }
                    } label: {
                        Image(systemName: "chevron.down.circle")
                    }
                }
            }
            .onChange(of: searchText) { _ in
                // Reset the marker when the search text changes.
                model.resetGraphics()
            }
            .task(id: submittedSearchText) {
                // Geocode the text when a search is submitted.
                if let submittedSearchText {
                    if let resultExtent = await model.geocodeSearch(address: submittedSearchText) {
                        // If found, zoom to the extent of the result's location.
                        viewpoint = Viewpoint(boundingGeometry: resultExtent)
                    } else {
                        // If no result was found, inform the user with an alert.
                        resultAlertIsShowing = true
                    }
                }

                submittedSearchText = nil
            }
            .alert("No results found.", isPresented: $resultAlertIsShowing, actions: {})
    }
}

private extension GeocodeOfflineView {
    /// The map view for the sample.
    struct GeocodeMapView: View {
        /// The view model for the sample.
        @ObservedObject var model: Model

        /// The action that ends the current search interaction.
        @Environment(\.dismissSearch) private var dismissSearch

        /// The current viewpoint of the map view.
        @Binding var viewpoint: Viewpoint

        /// The point on the map where the user tapped.
        @State private var tapLocation: Point?

        var body: some View {
            MapView(map: model.map, viewpoint: viewpoint, graphicsOverlays: [model.graphicsOverlay])
                .onViewpointChanged(kind: .centerAndScale) { viewpoint = $0 }
                .callout(placement: $model.calloutPlacement) { _ in
                    Text(model.calloutText)
                        .font(.callout)
                        .padding(8)
                }
                .onSingleTapGesture { _, mapPoint in
                    tapLocation = mapPoint
                }
                .onLongPressAndDragGesture { mapPoint in
                    model.calloutIsOffset = true
                    tapLocation = mapPoint
                } onEnded: {
                    // Reset the callout's offset when the gesture ends.
                    if let tapLocation {
                        model.calloutIsOffset = false
                        model.updateCalloutPlacement(to: tapLocation)
                    }
                    tapLocation = nil
                }
                .task(id: tapLocation) {
                    // Reverse geocode the tap location when it changes.
                    if let tapLocation {
                        dismissSearch()
                        await model.reverseGeocode(mapPoint: tapLocation)
                    }
                }
        }
    }
}

private extension MapView {
    /// Sets a closure to perform when the map view recognizes a long press and drag gesture.
    /// - Parameters:
    ///   - action: The closure to perform when the gesture is recognized.
    ///   - onEnded: The closure to perform when the gesture ends.
    /// - Returns: A new `View` object.
    func onLongPressAndDragGesture(
        perform action: @escaping (Point) -> Void,
        onEnded: @escaping () -> Void
    ) -> some View {
        self
            .onLongPressGesture { _, mapPoint in
                action(mapPoint)
            }
            .gesture(
                LongPressGesture()
                    .simultaneously(with: DragGesture())
                    .onEnded { _ in
                        onEnded()
                    }
            )
    }
}

Your browser is no longer supported. Please upgrade your browser for the best experience. See our browser deprecation post for more details.