Learn how to find an address or place with a search bar and the geocoding service
Geocoding is the process of converting address or place
In this tutorial, you use a search bar in the user interface to access the Geocoding service and search for addresses and places.
Prerequisites
Before starting this tutorial:
-
You need an ArcGIS Location Platform or ArcGIS Online account.
-
Your system meets the system requirements.
Set up authentication
To access the secure ArcGIS location services
You can implement API key authentication or user authentication in this tutorial. Compare the differences below:
API key authentication
- Users are not required to sign in.
- Requires creating an API key credential
API key credentials are an item that contains the parameters used to create and manage long-lived access tokens for API key authentication. They are a type of developer credential. with the correct privileges. - API keys
An API key is a long-lived access token created using API key credentials. They are valid for up to one year and are typically embedded directly into client applications. are long-lived access tokens. - Service usage is billed to the API key owner/developer.
- Simplest authentication method to implement.
- Recommended approach for new ArcGIS developers.
Learn more in API key authentication.
User authentication
- Users are required to sign in with an ArcGIS account
An ArcGIS account is an identity with a user type and set of privileges that can access specific ArcGIS products, tools, APIs, services, and resources. The main account types that can be used for development are an ArcGIS Location Platform account, ArcGIS Online account, and ArcGIS Enterprise account. ArcGIS Location Platform and ArcGIS Online accounts are also associated with a subscription. . - User accounts must have privilege
Privileges are a set of permissions assigned to ArcGIS accounts, developer credentials, and applications that grant access to secure resources and functionality in ArcGIS. to access the ArcGIS servicesA service, also known as an ArcGIS service, is software that supports an ArcGIS REST API and provides geospatial functionality or data. A service can be hosted by Esri or in ArcGIS Enterprise. used in application. - Requires creating OAuth credentials
OAuth credentials are an item that contains parameters required to implement user authentication or app authentication, including a .client_id,client_secret, and redirect URIs. They are a type of developer credential. - Application uses a redirect URL and client ID.
- Service usage is billed to the organization of the user signed into the application.
Learn more in User authentication.
To complete this tutorial, click on the tab in the switcher below for your authentication type of choice, either API key authentication or User authentication.
Create a new API key access token
-
Complete the Create an API key tutorial and create an API key with the following privilege(s)
Privileges are a set of permissions assigned to ArcGIS accounts, developer credentials, and applications that grant access to secure resources and functionality in ArcGIS. :- Privileges
- Location services > Basemaps
- Location services > Geocoding
- Privileges
-
Copy and paste the API key access token into a safe location. It will be used in a later step.
Develop or Download
You have two options for completing this tutorial:
Option 1: Develop the code
To start the tutorial, complete the Display a map tutorial. This creates a map to display the Santa Monica Mountains in California using the topographic basemap from the ArcGIS basemap styles service
Continue with the following instructions to add a search bar to the user interface and search for an address or place using the ArcGIS Geocoding service
Set developer credentials
If you implemented API key authenticationLocatorTask. To create an API Key access token that has the Basemaps and Geocoding privileges, see the Set up authentication step and then follow the instructions below.
Pass your API Key access token to the ArcGISEnvironment.
-
In the Project Navigator, click MainApp.swift.
-
Set the
ArcGISproperty with your API key access token.Environment.api Key MainApp.swiftUse dark colors for code blocks ArcGISEnvironment.apiKey = APIKey("<#YOUR-ACCESS-TOKEN#>")
Best Practice: The access token is stored directly in the code as a convenience for this tutorial. Do not store credentials directly in source code in a production environment.
Update the map
-
In Xcode, in the Project Navigator, click ContentView.swift.
-
In the editor, change the map and viewpoint into two separate
@variables so that the viewpoint can be changed as the geocode results change.State ContentView.swiftUse dark colors for code blocks 55 56 63Change line Change line Change line Change line Change line Change line struct ContentView: View { @State private var map = Map(basemapStyle: .arcGISImagery) @State private var viewpoint: Viewpoint? = Viewpoint( latitude: 34.02700, longitude: -118.80500, scale: 72_000 ) -
Create a private class named
Modelof typeObservableand add aObject @variable of theState Object Modelto theContent. See the programming patterns page for more information on how to manage states.View ContentView.swiftUse dark colors for code blocks 16 17 18 19 23 24 25 27 28Add line. Add line. Add line. Add line. import SwiftUI import ArcGIS private class Model: ObservableObject { } struct ContentView: View { @StateObject private var model = Model() } -
Create a
GraphicsOverlaynamedgraphicsin theOverlay Modelclass. A graphics overlayA graphics overlay is a client-side, temporary container of graphics to display on a map view or scene view. is a container for graphicsA graphic is a visual element composed of a geometry, symbol, and attributes that is displayed on a map or scene. .A graphics overlay
A graphics overlay is a client-side, temporary container of graphics to display on a map view or scene view. is a container for graphicsA graphic is a visual element composed of a geometry, symbol, and attributes that is displayed on a map or scene. . It is used with a map viewA map view is a user interface that displays map layers and graphics in 2D. It controls the area (extent) of the map that is visible and supports user interactions such as pan and zoom. to display graphics on a mapA map is a collection of layers that are displayed in 2D. It is typically composed of a basemap layer and data layers. . You can add more than one graphics overlay to a map view. Graphics overlays are displayed on top of all the other layersA layer is a reference to a collection of geographic data that is used to access and display data. The data for layers are typically provided by the basemap layer service and data services. .ContentView.swiftUse dark colors for code blocks 20 21 23 24Add line. private class Model: ObservableObject { let graphicsOverlay: GraphicsOverlay } -
Lastly, add the viewpoint and graphics overlay to the map view
A map view is a user interface that displays map layers and graphics in 2D. It controls the area (extent) of the map that is visible and supports user interactions such as pan and zoom. .ContentView.swiftUse dark colors for code blocks 88 89 91 92Change line var body: some View { MapView(map: map, viewpoint: viewpoint, graphicsOverlays: [model.graphicsOverlay]) }
Add graphics
Graphics are added as a visual means to display the search result on the map
-
Create a private property named
textin theGraphic Modelclass. This graphic will be used to display the result's text label.A
TextSymbolis used to display text at a location on the map view.ContentView.swiftUse dark colors for code blocks 20 21 22 23 35 36Add line. Add line. Add line. Add line. Add line. Add line. Add line. Add line. Add line. Add line. Add line. private class Model: ObservableObject { let graphicsOverlay: GraphicsOverlay let textGraphic: Graphic = { let textSymbol = TextSymbol( text: "", color: .black, size: 14, horizontalAlignment: .center, verticalAlignment: .bottom ) textSymbol.backgroundColor = .white return Graphic(symbol: textSymbol) }() } -
Create a private property named
markerin theGraphic Modelclass. This graphic will be used to display the result's location.A
SimpleMarkerSymbolis used to display a location on the map view.ContentView.swiftUse dark colors for code blocks 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 44 45Add line. Add line. Add line. Add line. Add line. Add line. Add line. Add line. private class Model: ObservableObject { let graphicsOverlay: GraphicsOverlay let textGraphic: Graphic = { let textSymbol = TextSymbol( text: "", color: .black, size: 14, horizontalAlignment: .center, verticalAlignment: .bottom ) textSymbol.backgroundColor = .white return Graphic(symbol: textSymbol) }() let markerGraphic: Graphic = { let markerSymbol = SimpleMarkerSymbol( style: .square, color: .red, size: 14 ) return Graphic(symbol: markerSymbol) }() } -
Create an
initfunction for theModelclass. Create aGraphicswith theOverlay textandGraphic markerand assign it to the model's graphics overlay. This function will be called whenGraphic Modelis initialized.Because
textandGraphic markerhaven't yet specified aGraphic Geometry, they will not be visible.ContentView.swiftUse dark colors for code blocks 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 48 49Add line. Add line. Add line. private class Model: ObservableObject { let graphicsOverlay: GraphicsOverlay let textGraphic: Graphic = { let textSymbol = TextSymbol( text: "", color: .black, size: 14, horizontalAlignment: .center, verticalAlignment: .bottom ) textSymbol.backgroundColor = .white return Graphic(symbol: textSymbol) }() let markerGraphic: Graphic = { let markerSymbol = SimpleMarkerSymbol( style: .square, color: .red, size: 14 ) return Graphic(symbol: markerSymbol) }() init() { graphicsOverlay = GraphicsOverlay(graphics: [textGraphic, markerGraphic]) } }
Create a locator task with geocode parameters
Geocoding is implemented with a locator
-
Create a
LocatorTaskproperty in theModel, namedlocator, based on the ArcGIS Geocoding service hosted by ESRI.A locator task is used to convert an address to a point
A point is a type of geometry containing a single set of (geocode) or vice-versa (reverse geocodex,ycoordinates and a spatial reference.Reverse geocoding is the process of converting a point to its nearest address or place. ). An address includes any type of information that distinguishes a place. A locatorA locator is an ArcGIS dataset that stores address information and the rules for translating descriptions of places (such as street addresses or place names) into spatial data that can be displayed on a map. involves finding matching locations for a given address. Reverse-geocoding is the opposite and finds the closest address for a given point.ContentView.swiftUse dark colors for code blocks 20 21 22 23 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 53Add line. Add line. Add line. private class Model: ObservableObject { let graphicsOverlay: GraphicsOverlay let locator = LocatorTask( url: URL(string: "https://geocode-api.arcgis.com/arcgis/rest/services/World/GeocodeServer")! ) let textGraphic: Graphic = { let textSymbol = TextSymbol( text: "", color: .black, size: 14, horizontalAlignment: .center, verticalAlignment: .bottom ) textSymbol.backgroundColor = .white return Graphic(symbol: textSymbol) }() let markerGraphic: Graphic = { let markerSymbol = SimpleMarkerSymbol( style: .square, color: .red, size: 14 ) return Graphic(symbol: markerSymbol) }() init() { graphicsOverlay = GraphicsOverlay(graphics: [textGraphic, markerGraphic]) } } -
In the
Content, create a privateView Stringvariable namedsearchwith theText @property wrapper. This will hold the user input and be used to perform the geocode operation.State ContentView.swiftUse dark colors for code blocks 55 56 57 58 59 60 61 62 63 64 65 67 68 69 70 71 72 73 74Add line. struct ContentView: View { @StateObject private var model = Model() @State private var map = Map(basemapStyle: .arcGISImagery) @State private var viewpoint: Viewpoint? = Viewpoint( latitude: 34.02700, longitude: -118.80500, scale: 72_000 ) @State private var searchText: String = "" var body: some View { MapView(map: map, viewpoint: viewpoint, graphicsOverlays: [model.graphicsOverlay]) } } -
Create a private, asynchronous function named
geocode(with. This function will be called when the user inputs an address.:) ContentView.swiftUse dark colors for code blocks 55 56 57 58 59 60 61 62 63 64 65 66 67 71 72 73 74 75 76 77 78Add line. Add line. Add line. struct ContentView: View { @StateObject private var model = Model() @State private var map = Map(basemapStyle: .arcGISImagery) @State private var viewpoint: Viewpoint? = Viewpoint( latitude: 34.02700, longitude: -118.80500, scale: 72_000 ) @State private var searchText: String = "" private func geocode(with searchText: String) async throws { } var body: some View { MapView(map: map, viewpoint: viewpoint, graphicsOverlays: [model.graphicsOverlay]) } } -
Within the new function, create
GeocodeParameters, and its attributes as follows:- Specify which attributes to return with
add.Result Attribute Name *is used to return all attributes. - Set the maximum number of results to be returned with
max. In this tutorial, only return the best match by passing inResults 1. Results are ordered byscore, so just returning the first result will return the highest scoring result. - Set the spatial reference
A spatial reference is a set of parameters, typically defined by a WKID, that define the coordinate system and spatial properties for geographic data. Applications use a spatial reference to correctly display the position of geographic data in a map or scene. withoutput. By default the output spatial reference is determined by the geocode service. For optimal performance when displaying the geocode result, ensure the returned coordinates match those of the map view by providingSpatial Reference mapas a parameter.View.spatial Reference
When geocoding an address, you can optionally provide
GeocodeParametersto control certain aspects of the geocoding operation, and specify the kinds of results to return from the locator task.ContentView.swiftUse dark colors for code blocks 68 69 74 75Add line. Add line. Add line. Add line. private func geocode(with searchText: String) async throws { let parameters = GeocodeParameters() parameters.addResultAttributeName("*") parameters.maxResults = 1 parameters.outputSpatialReference = map.spatialReference } - Specify which attributes to return with
-
Perform the geocode operation by calling
geocode(forand supplying the search text and the geocode parameters. The result obtained from the geocode operation will be displayed as a graphicSearch Text :using :) A graphic is a visual element composed of a geometry, symbol, and attributes that is displayed on a map or scene. in the map view's graphics overlayA graphics overlay is a client-side, temporary container of graphics to display on a map view or scene view. .ContentView.swiftUse dark colors for code blocks 68 69 70 71 72 73 74 85 86Add line. Add line. Add line. Add line. Add line. Add line. Add line. Add line. Add line. Add line. private func geocode(with searchText: String) async throws { let parameters = GeocodeParameters() parameters.addResultAttributeName("*") parameters.maxResults = 1 parameters.outputSpatialReference = map.spatialReference let geocodeResults = try await model.locator.geocode(forSearchText: searchText, using: parameters) if let firstResult = geocodeResults.first, let extent = firstResult.extent, let location = firstResult.displayLocation, let symbol = model.textGraphic.symbol as? TextSymbol { viewpoint = Viewpoint(boundingGeometry: extent) model.markerGraphic.geometry = location model.textGraphic.geometry = location symbol.text = firstResult.label } }
Add a search bar to the UI
To search an address using the application, add a UI element to prompt the user for text input.
-
In the
body, add anoverlayto theMap. Set theView alignmentto the top, add padding all around, and set the background.ContentView.swiftUse dark colors for code blocks 88 89 90 91 97 98Add line. Add line. Add line. Add line. Add line. var body: some View { MapView(map: map, viewpoint: viewpoint, graphicsOverlays: [model.graphicsOverlay]) .overlay(alignment: .top) { .padding(EdgeInsets(top: 60, leading: 10, bottom: 10, trailing: 10)) .background(.thinMaterial, ignoresSafeAreaEdges: .horizontal) } } -
Within the overlay, add the following:
Text: Pass in "Enter address" as theField titleand theKey searchvariable as a binding for theText textparameterSpacer(): Add space in between the text field and button.Button: Label it "Search" and using aTaskmethod, call thegeocode(withfunction and pass in:) searchText
ContentView.swiftUse dark colors for code blocks 88 89 90 91 92 93 103 104 105 106 107 108Add line. Add line. Add line. Add line. Add line. Add line. Add line. Add line. Add line. var body: some View { MapView(map: map, viewpoint: viewpoint, graphicsOverlays: [model.graphicsOverlay]) .overlay(alignment: .top) { HStack { TextField("Enter address", text: $searchText) Spacer() Button("Search") { Task { try await geocode(with: searchText) } } } .padding(EdgeInsets(top: 60, leading: 10, bottom: 10, trailing: 10)) .background(.thinMaterial, ignoresSafeAreaEdges: .horizontal) } }
Run the solution
Press Command + R to run the app.
If you are using the Xcode simulator your system must meet these minimum requirements: macOS 14 (Sonoma), Xcode 16, iOS 18. If you are using a physical device, then refer to the system requirements.
You should see a search box at the top of the map. Search for an address by entering an address and tap the Search button. The result of the search should display on the map as a red square with the address displayed on top.
- 1000 5th Ave, New York, NY 10028
- Great Russell St, Bloomsbury, London WC1B 3DG, United Kingdom
- 13-9 Uenokoen, Taito City, Tokyo 110-8712, Japan
- Av. Paulista, 1578 – Bela Vista, São Paulo, Brasil
Alternatively, you can download the tutorial solution, as follows.
Option 2: Download the solution
-
Click the
Download solutionlink under Solution and unzip the file to a location on your machine. -
Open the
.xcodeprojfile in Xcode.
Since the downloaded solution does not contain authentication credentials, you must add the developer credentials that you created in the Set up authentication section.
Set developer credentials in the solution
To allow your app users to access ArcGIS location services
Pass your API Key access token to the ArcGISEnvironment.
-
In the Project Navigator, click MainApp.swift.
-
Set the
AuthenticationtoMode .api.Key MainApp.swiftUse dark colors for code blocks // Change the `AuthenticationMode` to `.apiKey` if your application uses API key authentication. private var authenticationMode: AuthenticationMode { .apiKey } -
Set the
apiproperty with your API key access token.Key MainApp.swiftUse dark colors for code blocks // Please enter an API key access token if your application uses API key authentication. private let apiKey = APIKey("<#YOUR-ACCESS-TOKEN#>")
Best Practice: The access token is stored directly in the code as a convenience for this tutorial. Do not store credentials directly in source code in a production environment.
Run the solution
Press Command + R to run the app.
If you are using the Xcode simulator your system must meet these minimum requirements: macOS 14 (Sonoma), Xcode 16, iOS 18. If you are using a physical device, then refer to the system requirements.
You should see a search box at the top of the map. Search for an address by entering an address and tap the Search button. The result of the search should display on the map as a red square with the address displayed on top.
- 1000 5th Ave, New York, NY 10028
- Great Russell St, Bloomsbury, London WC1B 3DG, United Kingdom
- 13-9 Uenokoen, Taito City, Tokyo 110-8712, Japan
- Av. Paulista, 1578 – Bela Vista, São Paulo, Brasil
What's next?
Learn how to use additional API features, ArcGIS location services, and ArcGIS tools in these tutorials: