Offline geocode

View on GitHub
Sample viewer app

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

Offline geocode sample

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 text field or tap the arrow on the right and select from the list to geocode the address and view the result on the map. Tap the location you want to reverse geocode. Tap and hold to create a pin on the map and pan while holding to get real-time geocoding.

How it works

  1. Create an AGSLocatorTask object.
  2. Set up AGSGeocodeParameters and call AGSGeocode(withSearchText:parameters:completion:) to get geocode results.

Relevant API

  • AGSGeocodeParameters
  • AGSGeocodeResult
  • AGSLocatorTask
  • AGSReverseGeocodeParameters

Offline data

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

Tags

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

Sample Code

OfflineGeocodeViewController.swiftSanDiegoAddressesViewController.swift
                                                                                                                                                                                                                                                                                        
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
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
// Copyright 2016 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 UIKit
import ArcGIS

class GeocodeOfflineViewController: UIViewController, AGSGeoViewTouchDelegate, UISearchBarDelegate, UIAdaptivePresentationControllerDelegate, SanDiegoAddressesViewControllerDelegate {
    @IBOutlet private var mapView: AGSMapView!
    @IBOutlet private var button: UIButton!
    @IBOutlet private var searchBar: UISearchBar!

    private var locatorTask: AGSLocatorTask!
    private var geocodeParameters: AGSGeocodeParameters!
    private var reverseGeocodeParameters: AGSReverseGeocodeParameters!
    private let graphicsOverlay = AGSGraphicsOverlay()
    private var locatorTaskOperation: AGSCancelable!
    private var magnifierOffset: CGPoint!
    private var longPressedAndMoving = false

    override func viewDidLoad() {
        super.viewDidLoad()

        // add the source code button item to the right of navigation bar
        (self.navigationItem.rightBarButtonItem as! SourceCodeBarButtonItem).filenames = ["OfflineGeocodeViewController", "SanDiegoAddressesViewController"]

        // create a local tiled layer using tile package
        let path = Bundle.main.path(forResource: "streetmap_SD", ofType: "tpk")!
        let localTiledLayer = AGSArcGISTiledLayer(tileCache: AGSTileCache(fileURL: URL(fileURLWithPath: path)))

        // instantiate map and add the local tiled layer
        let map = AGSMap()
        map.operationalLayers.add(localTiledLayer)

        // assign the map to the map view
        self.mapView.map = map
        // register self as the touch delgate for the map view
        // will need that to show callout
        self.mapView.touchDelegate = self

        // add the graphics overlay to the map view
        // will add the resulting graphics to this overlay
        self.mapView.graphicsOverlays.add(self.graphicsOverlay)

        // initialize locator task
        self.locatorTask = AGSLocatorTask(name: "san-diego-locator")

        // initialize geocode params
        self.geocodeParameters = AGSGeocodeParameters()
        self.geocodeParameters.resultAttributeNames.append(contentsOf: ["Match_addr"])
        self.geocodeParameters.minScore = 75

        // initialize reverse geocode params
        self.reverseGeocodeParameters = AGSReverseGeocodeParameters()
        self.reverseGeocodeParameters.maxResults = 1
        self.reverseGeocodeParameters.resultAttributeNames.append(contentsOf: ["*"])

        // add self as the observer for the keyboard show notification
        // will display a button every time keyboard is display so the user
        // can tap and cancel search and hide the keyboard
        NotificationCenter.default.addObserver(self, selector: #selector(GeocodeOfflineViewController.keyboardWillShow(_:)), name: UIResponder.keyboardWillShowNotification, object: nil)

        // zoom to San Diego
        self.mapView.setViewpointCenter(AGSPoint(x: -13042254.715252, y: 3857970.236806, spatialReference: .webMercator()), scale: 2e4)

        // enable magnifier for better experience while using tap n hold to add a location
        self.mapView.interactionOptions.isMagnifierEnabled = true

        // the total amount by which we will need to offset the callout along y-axis
        // to show it correctly centered on the pushpin's head in the magnifier
        let img = UIImage(named: "Magnifier", in: AGSBundle(), compatibleWith: nil)!
        self.magnifierOffset = CGPoint(x: 0, y: -img.size.height)
    }

    private func geocodeSearchText(_ text: String) {
        // hide keyboard
        self.hideKeyboard()

        // dismiss the callout if already visible
        self.mapView.callout.dismiss()

        // remove all previous graphics
        self.graphicsOverlay.graphics.removeAllObjects()

        // perform geocode with the input
        self.locatorTask.geocode(withSearchText: text, parameters: self.geocodeParameters) { [weak self]  (results: [AGSGeocodeResult]?, error: Error?) in
            guard let self = self else {
                return
            }

            if let error = error {
                self.presentAlert(error: error)
            } else {
                // if a result was returned display the graphic on the map view
                // using the first result, as it is the more relevant
                if let result = results?.first {
                    let graphic = self.makeGraphic(point: result.displayLocation!, attributes: result.attributes)
                    self.graphicsOverlay.graphics.add(graphic)

                    // zoom to the extent of the graphic
                    self.mapView.setViewpointGeometry(result.displayLocation!.extent, completion: nil)
                } else {
                    // if no result found, inform the user
                    self.presentAlert(message: "No results found")
                }
            }
        }
    }

    private func reverseGeocode(point: AGSPoint) {
        // clear the search bar text to give feedback that the graphic
        // is based on the tap and not search
        self.searchBar.text = ""

        // remove all previous graphics
        self.graphicsOverlay.graphics.removeAllObjects()

        // normalize the point
        let normalizedPoint = AGSGeometryEngine.normalizeCentralMeridian(of: point) as! AGSPoint

        // cancel all previous operations
        if self.locatorTaskOperation != nil {
            self.locatorTaskOperation.cancel()
        }

        // create a graphic and add to the overlay
        let graphic = self.makeGraphic(point: normalizedPoint)
        self.graphicsOverlay.graphics.add(graphic)

        // perform reverse geocode
        self.locatorTaskOperation = self.locatorTask.reverseGeocode(withLocation: normalizedPoint, parameters: self.reverseGeocodeParameters) { [weak self] (results: [AGSGeocodeResult]?, error: Error?) in
            if let error = error as NSError? {
                if error.code != NSUserCancelledError {
                    // print error instead alerting to avoid disturbing the flow
                    print(error.localizedDescription)
                }
            } else if let result = results?.first {
                // if a result is found extract the required attributes
                // assign the attributes to the graphic
                // and show the callout
                let cityString = result.attributes?["City"] as? String ?? ""
                let streetString = result.attributes?["Street"] as? String ?? ""
                let stateString = result.attributes?["State"] as? String ?? ""
                graphic.attributes.addEntries(from: ["Match_addr": "\(streetString) \(cityString) \(stateString)"])
                self?.showCalloutForGraphic(graphic, tapLocation: normalizedPoint, animated: false, offset: self!.longPressedAndMoving)
                return
            } else {
                // no result was found
                // using print in log instead of alert to
                // avoid breaking the flow
                print("No address found")

                // dismiss the callout if already visible
                self?.mapView.callout.dismiss()
            }
            // in case of error or no results, remove the graphics
            self?.graphicsOverlay.graphics.remove(graphic)
        }
    }

    // method returns a graphic object for the point and attributes provided
    private func makeGraphic(point: AGSPoint, attributes: [String: Any]? = nil) -> AGSGraphic {
        let markerImage = #imageLiteral(resourceName: "RedMarker")
        let symbol = AGSPictureMarkerSymbol(image: markerImage)
        symbol.leaderOffsetY = markerImage.size.height / 2
        symbol.offsetY = markerImage.size.height / 2
        return AGSGraphic(geometry: point, symbol: symbol, attributes: attributes)
    }

    // method to show the callout for the provided graphic, with tap location details
    private func showCalloutForGraphic(_ graphic: AGSGraphic, tapLocation: AGSPoint, animated: Bool, offset: Bool) {
        self.mapView.callout.title = graphic.attributes["Match_addr"] as? String
        self.mapView.callout.isAccessoryButtonHidden = true

        if !offset {
            self.mapView.callout.show(for: graphic, tapLocation: tapLocation, animated: animated)
        } else {
            self.mapView.callout.show(at: tapLocation, screenOffset: self.magnifierOffset, rotateOffsetWithMap: false, animated: animated)
        }
    }

    // MARK: - AGSGeoViewTouchDelegate

    func geoView(_ geoView: AGSGeoView, didTapAtScreenPoint screenPoint: CGPoint, mapPoint: AGSPoint) {
        // dismiss the callout if already visible
        self.mapView.callout.dismiss()

        // get the graphics at the tap location
        self.mapView.identify(self.graphicsOverlay, screenPoint: screenPoint, tolerance: 12, returnPopupsOnly: false, maximumResults: 1) { (result: AGSIdentifyGraphicsOverlayResult) in
            if let error = result.error {
                self.presentAlert(error: error)
            } else if let graphic = result.graphics.first {
                // show the callout for the first graphic found
                self.showCalloutForGraphic(graphic, tapLocation: mapPoint, animated: true, offset: false)
            }
        }
    }

    func geoView(_ geoView: AGSGeoView, didLongPressAtScreenPoint screenPoint: CGPoint, mapPoint: AGSPoint) {
        self.longPressedAndMoving = true
        // on long press perform reverse geocode
        self.reverseGeocode(point: mapPoint)
    }

    func geoView(_ geoView: AGSGeoView, didMoveLongPressToScreenPoint screenPoint: CGPoint, mapPoint: AGSPoint) {
        // perform geocode for the updated location
        self.reverseGeocode(point: mapPoint)
    }

    func geoView(_ geoView: AGSGeoView, didEndLongPressAtScreenPoint screenPoint: CGPoint, mapPoint: AGSPoint) {
        self.longPressedAndMoving = false
        // the callout right now will be at an offset
        // update the callout to show on top of the graphic
        self.mapView.touchDelegate?.geoView!(self.mapView, didTapAtScreenPoint: screenPoint, mapPoint: mapPoint)
    }

    // MARK: - UISearchBar delegates

    func searchBarSearchButtonClicked(_ searchBar: UISearchBar) {
        self.geocodeSearchText(searchBar.text!)
    }

    func searchBar(_ searchBar: UISearchBar, textDidChange searchText: String) {
        self.graphicsOverlay.graphics.removeAllObjects()
    }

    func searchBarResultsListButtonClicked(_ searchBar: UISearchBar) {
        self.performSegue(withIdentifier: "AddressesListSegue", sender: self)
    }

    // MARK: - Actions
    @objc
    func keyboardWillShow(_ sender: AnyObject) {
        self.button.isHidden = false
    }

    @IBAction func hideKeyboard() {
        self.searchBar.resignFirstResponder()
        self.button.isHidden = true
    }

    // MARK: - Navigation

    override func prepare(for segue: UIStoryboardSegue, sender: Any?) {
        if segue.identifier == "AddressesListSegue" {
            let controller = segue.destination as! SanDiegoAddressesViewController
            controller.presentationController?.delegate = self
            controller.popoverPresentationController?.sourceView = self.view
            controller.popoverPresentationController?.sourceRect = self.searchBar.frame
            controller.preferredContentSize = CGSize(width: 300, height: 200)
            controller.delegate = self
        }
    }

    // MARK: - UIAdaptivePresentationControllerDelegate

    func adaptivePresentationStyle(for controller: UIPresentationController, traitCollection: UITraitCollection) -> UIModalPresentationStyle {
        return UIModalPresentationStyle.none
    }

    // MARK: - SanDiegoAddressesViewControllerDelegate

    // when the user selects an address from the list
    // update the search bar text, geocode the selected address
    func sanDiegoAddressesViewController(_ sanDiegoAddressesViewController: SanDiegoAddressesViewController, didSelectAddress address: String) {
        self.searchBar.text = address
        self.geocodeSearchText(address)
        self.dismiss(animated: true)
    }
}

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