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.
Create new OAuth credentials to access the secure resources used in this tutorial.
-
Complete the Create OAuth credentials for user authentication tutorial to obtain a Client ID and Redirect URL.
A
Client IDuniquely identifies your app on the authenticating server. If the server cannot find an app with the provided Client ID, it will not proceed with authentication.The
Redirect URL(also referred to as a callback url) is used to identify a response from the authenticating server when the system returns control back to your app after an OAuth login. Since it does not necessarily represent a valid endpoint that a user could navigate to, the redirect URL can use a custom scheme, such asmy-app://auth. It is important to make sure the redirect URL used in your app’s code matches a redirect URL configured on the authenticating server. -
Copy and paste the Client ID and Redirect URL into a safe location. They will be used in a later step.
All users that access this application need account privileges
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
ArcGISEnvironment.apiKeyproperty with your API key access token.MainApp.swiftArcGISEnvironment.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.
Use the Authenticator toolkit component to manage your OAuth credentialsclient_id, client_secret, and redirect URIs. They are a type of developer credential. ArcGISEnvironment.
-
In the Project Navigator, click MainApp.swift.
-
Set your
PortalURL,clientIDandredirectURLvalues.MainApp.swiftauthenticator = Authenticator(oAuthUserConfigurations: [OAuthUserConfiguration(portalURL: URL(string: "<#YOUR-PORTAL-URL#>")!,clientID: ""<#YOUR-CLIENT-ID#>"",redirectURL: URL(string: "<#YOUR-REDIRECT-URL#>")!)])ArcGISEnvironment.authenticationManager.handleChallenges(using: authenticator)
Best Practice: The OAuth credentials are 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
@Statevariables so that the viewpoint can be changed as the geocode results change.ContentView.swiftstruct 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 typeObservableObjectand add a@StateObjectvariable of theModelto theContentView. See the programming patterns page for more information on how to manage states.ContentView.swiftimport SwiftUIimport ArcGISprivate class Model: ObservableObject {}struct ContentView: View {@StateObject private var model = Model()} -
Create a
GraphicsOverlaynamedgraphicsOverlayin theModelclass. 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.swiftprivate 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.swiftvar 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
textGraphicin theModelclass. 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.swift19 collapsed lines// Copyright 2024 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 ArcGISprivate class Model: ObservableObject {let graphicsOverlay: GraphicsOverlaylet textGraphic: Graphic = {let textSymbol = TextSymbol(text: "",color: .black,size: 14,horizontalAlignment: .center,verticalAlignment: .bottom)textSymbol.backgroundColor = .whitereturn Graphic(symbol: textSymbol)}()}19 collapsed linesstruct 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)var body: some View {MapView(map: map, viewpoint: viewpoint, graphicsOverlays: [model.graphicsOverlay])}} -
Create a private property named
markerGraphicin theModelclass. This graphic will be used to display the result’s location.A
SimpleMarkerSymbolis used to display a location on the map view.ContentView.swift19 collapsed lines// Copyright 2024 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 ArcGISprivate class Model: ObservableObject {let graphicsOverlay: GraphicsOverlaylet textGraphic: Graphic = {let textSymbol = TextSymbol(text: "",color: .black,size: 14,horizontalAlignment: .center,verticalAlignment: .bottom)textSymbol.backgroundColor = .whitereturn Graphic(symbol: textSymbol)}()let markerGraphic: Graphic = {let markerSymbol = SimpleMarkerSymbol(style: .square,color: .red,size: 14)return Graphic(symbol: markerSymbol)}()}19 collapsed linesstruct 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)var body: some View {MapView(map: map, viewpoint: viewpoint, graphicsOverlays: [model.graphicsOverlay])}} -
Create an
initfunction for theModelclass. Create aGraphicsOverlaywith thetextGraphicandmarkerGraphicand assign it to the model’s graphics overlay. This function will be called whenModelis initialized.Because
textGraphicandmarkerGraphichaven’t yet specified aGeometry, they will not be visible.ContentView.swift19 collapsed lines// Copyright 2024 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 ArcGISprivate class Model: ObservableObject {let graphicsOverlay: GraphicsOverlaylet textGraphic: Graphic = {let textSymbol = TextSymbol(text: "",color: .black,size: 14,horizontalAlignment: .center,verticalAlignment: .bottom)textSymbol.backgroundColor = .whitereturn 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])}}19 collapsed linesstruct 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)var body: some View {MapView(map: map, viewpoint: viewpoint, graphicsOverlays: [model.graphicsOverlay])}}
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.swift19 collapsed lines// Copyright 2024 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 ArcGISprivate class Model: ObservableObject {let graphicsOverlay: GraphicsOverlaylet 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 = .whitereturn 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])}}19 collapsed linesstruct 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)var body: some View {MapView(map: map, viewpoint: viewpoint, graphicsOverlays: [model.graphicsOverlay])}} -
In the
ContentView, create a privateStringvariable namedsearchTextwith the@Stateproperty wrapper. This will hold the user input and be used to perform the geocode operation.ContentView.swift54 collapsed lines// Copyright 2024 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 ArcGISprivate class Model: ObservableObject {let graphicsOverlay: GraphicsOverlaylet 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 = .whitereturn 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])}}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.swift54 collapsed lines// Copyright 2024 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 ArcGISprivate class Model: ObservableObject {let graphicsOverlay: GraphicsOverlaylet 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 = .whitereturn 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])}}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
addResultAttributeName.*is used to return all attributes. - Set the maximum number of results to be returned with
maxResults. In this tutorial, only return the best match by passing in1. 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. withoutputSpatialReference. 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 providingmapView.spatialReferenceas a parameter.
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.swift67 collapsed lines// Copyright 2024 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 ArcGISprivate class Model: ObservableObject {let graphicsOverlay: GraphicsOverlaylet 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 = .whitereturn 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])}}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 {let parameters = GeocodeParameters()parameters.addResultAttributeName("*")parameters.maxResults = 1parameters.outputSpatialReference = map.spatialReference}8 collapsed linesvar body: some View {MapView(map: map, viewpoint: viewpoint, graphicsOverlays: [model.graphicsOverlay])}} - Specify which attributes to return with
-
Perform the geocode operation by calling
geocode(forSearchText:using:)and supplying the search text and the geocode parameters. The result obtained from the geocode operation will be displayed as a graphicA 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.swift67 collapsed lines// Copyright 2024 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 ArcGISprivate class Model: ObservableObject {let graphicsOverlay: GraphicsOverlaylet 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 = .whitereturn 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])}}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 {let parameters = GeocodeParameters()parameters.addResultAttributeName("*")parameters.maxResults = 1parameters.outputSpatialReference = map.spatialReferencelet 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 = locationmodel.textGraphic.geometry = locationsymbol.text = firstResult.label}}8 collapsed linesvar body: some View {MapView(map: map, viewpoint: viewpoint, graphicsOverlays: [model.graphicsOverlay])}}
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 theMapView. Set thealignmentto the top, add padding all around, and set the background.ContentView.swift87 collapsed lines// Copyright 2024 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 ArcGISprivate class Model: ObservableObject {let graphicsOverlay: GraphicsOverlaylet 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 = .whitereturn 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])}}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 {let parameters = GeocodeParameters()parameters.addResultAttributeName("*")parameters.maxResults = 1parameters.outputSpatialReference = map.spatialReferencelet 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 = locationmodel.textGraphic.geometry = locationsymbol.text = firstResult.label}}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)}}2 collapsed lines} -
Within the overlay, add the following:
TextField: Pass in “Enter address” as thetitleKeyand thesearchTextvariable as a binding for thetextparameterSpacer(): Add space in between the text field and button.Button: Label it “Search” and using aTaskmethod, call thegeocode(with:)function and pass insearchText
ContentView.swift87 collapsed lines// Copyright 2024 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 ArcGISprivate class Model: ObservableObject {let graphicsOverlay: GraphicsOverlaylet 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 = .whitereturn 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])}}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 {let parameters = GeocodeParameters()parameters.addResultAttributeName("*")parameters.maxResults = 1parameters.outputSpatialReference = map.spatialReferencelet 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 = locationmodel.textGraphic.geometry = locationsymbol.text = firstResult.label}}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)}}2 collapsed lines}
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
AuthenticationModeto.apiKey.MainApp.swift// Change the `AuthenticationMode` to `.apiKey` if your application uses API key authentication.private var authenticationMode: AuthenticationMode { .apiKey } -
Set the
apiKeyproperty with your API key access token.MainApp.swift31 collapsed lines// Copyright 2022 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 ArcGISimport ArcGISToolkit@mainstruct MainApp: App {// The authentication mode.private enum AuthenticationMode {case apiKeycase user}// Change the `AuthenticationMode` to `.apiKey` if your application uses API key authentication.private var authenticationMode: AuthenticationMode { .apiKey }// Please enter an API key access token if your application uses API key authentication.private let apiKey = APIKey("<#YOUR-ACCESS-TOKEN#>")43 collapsed lines// Setup an `Authenticator` with OAuth configuration if your application uses OAuth credentials.@ObservedObject var authenticator = Authenticator(oAuthUserConfigurations: [OAuthUserConfiguration(// Please enter OAuth credentials for user authentication.portalURL: URL(string: "<#YOUR-PORTAL-URL#>")!,clientID: "<#YOUR-CLIENT-ID#>",redirectURL: URL(string: "<#YOUR-REDIRECT-URL#>")!)])func setAuthentication() {switch authenticationMode {case .apiKey:ArcGISEnvironment.apiKey = apiKeycase .user:ArcGISEnvironment.authenticationManager.arcGISAuthenticationChallengeHandler = authenticator}}init() {setAuthentication()}var body: some SwiftUI.Scene {WindowGroup {ContentView().authenticator(authenticator).ignoresSafeArea()}}}
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.
Use the Authenticator toolkit component to manage your OAuth credentialsclient_id, client_secret, and redirect URIs. They are a type of developer credential. ArcGISEnvironment.
-
In the Project Navigator, click MainApp.swift.
-
Set the
AuthenticationModeto.user.MainApp.swift// Change the `AuthenticationMode` to `.user` if your application uses OAuth credentials.private var authenticationMode: AuthenticationMode { .user } -
Set your
portalURL,clientIDandredirectURLvalues.MainApp.swift36 collapsed lines// Copyright 2022 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 ArcGISimport ArcGISToolkit@mainstruct MainApp: App {// The authentication mode.private enum AuthenticationMode {case apiKeycase user}// Change the `AuthenticationMode` to `.user` if your application uses OAuth credentials.private var authenticationMode: AuthenticationMode { .apiKey }// Please enter an API key access token if your application uses API key authentication.private let apiKey = APIKey("<#YOUR-ACCESS-TOKEN#>")// Setup an `Authenticator` with OAuth configuration if your application uses OAuth credentials.@ObservedObject var authenticator = Authenticator(oAuthUserConfigurations: [OAuthUserConfiguration(// Please enter OAuth credentials for user authentication.portalURL: URL(string: "<#YOUR-PORTAL-URL#>")!,clientID: "<#YOUR-CLIENT-ID#>",redirectURL: URL(string: "<#YOUR-REDIRECT-URL#>")!)])28 collapsed linesfunc setAuthentication() {switch authenticationMode {case .apiKey:ArcGISEnvironment.apiKey = apiKeycase .user:ArcGISEnvironment.authenticationManager.arcGISAuthenticationChallengeHandler = authenticator}}init() {setAuthentication()}var body: some SwiftUI.Scene {WindowGroup {ContentView().authenticator(authenticator).ignoresSafeArea()}}}
Best Practice: The OAuth credentials are 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: