Skip To Content ArcGIS for Developers Sign In Dashboard

Overview

You will learn: how to build an app to find addresses and places with the ArcGIS World Geocoding Service.

With the ArcGIS Runtime SDK for iOS you can easily find places and addresses all around the world. The process of matching locations or place names on the map to an address is referred to as geocoding. Your user can specify a location of interest or street address and see it on the map. You can use the ArcGIS World Geocoding Service as a locator which has the ability to search for places, business names and addresses, and supports many different input formats. You can also perform reverse geocoding where you pass in a point location or latitude and longitude and the locator will return the address it finds. With this functionality you can build powerful apps that allow users to easily find what they are looking for.

Locating addresses is a service with many features and options. Refer to Search for places (geocoding) if you would like to read more about the process and options.

This tutorial is a bit complex because you will define a user interface to handle user interaction. This demonstrates one of many possible methods for requesting user input. The method used here places the search bar at the top of the iOS device's screen.

Before you begin

Make sure you have installed the latest version of Xcode.

Reuse the starter project

If you have completed the Create a starter app tutorial, then copy the project into a new empty folder. Otherwise, download and unzip the project solution. Open the .xcodeproj file in Xcode. Run and verify the map displays in the device simulator.

Steps

Add a Search Bar to the app

  1. In the project navigator, find the Main.storyboard file. Add a Visual Effect View and Search Bar above the Map View (if you prefer to start with the UI already wired up, use this project and skip ahead to Search for an address below.).

  2. Right-click on the Search Bar and drag the delegate outlet to the View Controller.

  3. In the project navigator, find the ViewController.swift file. Add a class extension to specify that it implements the UISearchBarDelegate protocol.

    /** ADD **/
    extension ViewController: UISearchBarDelegate {
    
    }
    

Create an app configuration file

  1. Add a new swift file named AppConfiguration.swift. Use this file to specify constants that can be used by the app to connect to data and resources. Create a static URL that points to the ArcGIS World Geocoding Service. You will use this resource in future steps.

    /** ADD **/
    extension URL {
        static let worldGeocodingService = URL(string: "https://geocode.arcgis.com/arcgis/rest/services/World/GeocodeServer")!
    }
    

Alert the user

  1. Add a new method for presenting an alert message to the user.

    /** ADD **/
    private func present(alert message: String) {
        let alert = UIAlertController(
            title: nil,
            message: message,
            preferredStyle: .alert
        )
        let okay = UIAlertAction(
            title: "Okay",
            style: .default,
            handler: nil
        )
        alert.addAction(okay)
        self.present(alert, animated: true, completion: nil)
    }
    

Search for an address

  1. Create an AGSLocatorTask instance variable pointing to the ArcGIS World Geocoding Service.

    @IBOutlet weak var mapView: AGSMapView!
    
    /* ADD */
    private let locator: AGSLocatorTask = {
        let locator = AGSLocatorTask(url: .worldGeocodingService)
        locator.load(completion: nil)
        return locator
    }()
    
  2. Add a currentGeocodeOperation member variable to ViewController to track the current geocode operation. This cancelable reference is used to cancel an existing running geocode operation if a new one is performed instead.

    /** ADD **/
    private var currentGeocodeOperation: AGSCancelable?
    
  3. Add a new method named geocode to ViewController to perform a geocode operation that takes a search text String parameter. This method will handle the response by taking the first result and zooming the map to that location.

    /** ADD **/
    private func geocode(with searchText: String) {
    
        currentGeocodeOperation?.cancel()
    
        locator.load { [weak self] (error) in
            guard let self = self else { return }
    
            if let error = error {
                self.present(alert: error.localizedDescription)
                return
            }
    
            self.currentGeocodeOperation = self.locator.geocode(withSearchText: searchText) { [weak self] (results, error) in
                guard let self = self else { return }
    
                if let error = error {
                    self.present(alert: error.localizedDescription)
                    return
                }
    
                if let firstResult = results?.first, let extent = firstResult.extent {
                    self.mapView.setViewpointGeometry(extent)
                }
                else {
                    self.present(alert: "No results found for \(searchText).")
                }
            }
        }
    }
    
  4. Add a searchBarSearchButtonClicked delegate method to perform a search when the Search button is clicked using the text entered in the Search Bar.

    extension ViewController: UISearchBarDelegate {
        /** ADD **/
        func searchBarSearchButtonClicked(_ searchBar: UISearchBar) {
            guard let searchText = searchBar.text, !searchText.isEmpty else {
                self.present(alert: "Nothing to search!")
                return
            }
    
            geocode(with: searchText)
        }
    }
    
  5. Run the app. Press Command-R to run the app in the iOS Simulator.

    (Note, as of 100.8 Runtime supports Metal. In order to run your app in a simulator you must meet some minimum requirements. You must be developing on macOS Catalina, using Xcode 11, and simulating iOS 13. If you do not meet these requirements, you should run the app on a physical iOS device.)

Congratulations, you're done!

The map should load and display a search bar at the top. Enter some text in the search bar and press enter. The map will zoom to the first geocoded result. Compare your solution with our completed solution project.

Challenge

Show a graphic

The map zooms to the search result, but there is nothing placed on the map to show the actual location. Try using the search result's displayLocation property to create a point-based AGSGraphic to display on the map. You will need to add an AGSGraphicsOverlay to the mapView to display the graphic.

Multiple results

The geocode() method has a version that takes additional parameters. Try using AGSGeocodeParameters and varying setMaxResults to show the user multiple possible matches. Can you come up with a UI that allows the user to select a possible match?

Geocoding parameters

Can you discover other geocoding parameters available to the locator task? For example, limit the search area to the visible extent of the map view.

Show suggestions

The ArcGIS Online geocoder includes functionality to return suggestions for a partially-typed search string. See if you can come up with a UI to present suggestions to the user as they type in the search bar. Investigate the AGSGeocoder.suggest() methods to get AGSSuggestResults. You then pass the selected suggestion to the AGSLocatorTask. This Open Source App might provide some inspiration.