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.
-
Ensure your development environment meets the system requirements.
Optionally, you may want to install the ArcGIS Maps SDK for .NET to get access to project templates in Visual Studio (Windows only) and offline copies of the NuGet packages.
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
Open a Visual Studio solution
- Open the Visual Studio solution you created by completing the Display a map tutorial.
- Continue following the instructions to:
- Configure authentication in your app so that your app users can access the ArcGIS Geocoding service
A geocoding service is a service that can search for addresses, place addresses, businesses, reverse geocode coordinates to addresses, provide suggestions for places, and perform bulk geocoding. It is hosted by Esri as the ArcGIS Geocoding service and can also be hosted in ArcGIS Enterprise. to find addresses and show their location on the map. - Add functionality to search for an address or place using the ArcGIS Geocoding service
A geocoding service is a service that can search for addresses, place addresses, businesses, reverse geocode coordinates to addresses, provide suggestions for places, and perform bulk geocoding. It is hosted by Esri as the ArcGIS Geocoding service and can also be hosted in ArcGIS Enterprise. .
- Configure authentication in your app so that your app users can access the ArcGIS Geocoding service
Update the tutorial name used in the project (optional)
The Visual Studio solution, project, and the namespace for all classes currently use the name DisplayAMap. Follow the steps below if you prefer the name to reflect the current tutorial. These steps are not required, your code will still work if you keep the original name.
The tutorial instructions and code use the name SearchForAnAddress for the solution, project, and namespace. You can choose any name you like, but it should be the same for each of these.
-
Update the name for the solution and the project.
- In Visual Studio, in the Solution Explorer, right-click the solution name and choose Rename. Provide the new name for your solution.
- In the Solution Explorer, right-click the project name and choose Rename. Provide the new name for your project.
-
Rename the namespace used by classes in the project.
- In the Solution Explorer, expand the project node.
- Double-click MapViewModel.cs in the Solution Explorer to open the file.
- In the
MapViewModelclass, double-click the namespace name (DisplayAMap) to select it, and then right-click and choose Rename…. - Provide the new name for the namespace.
- Click Apply in the Rename: DisplayAMap window that appears in the upper-right of the code window. This will rename the namespace throughout your project.
-
Build the project.
- Choose Build > Build solution (or press <F6>).
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.
-
In the Solution Explorer, expand the node for App.xaml, and double-click App.xaml.cs to open it.
-
In the App class, in the override for the
OnStartup()function, set theApiKeyproperty onArcGISRuntimeEnvironmentwith your new API key (with additional privileges besides basemap).App.xaml.cspublic partial class App : Application{protected override void OnStartup(StartupEventArgs e){base.OnStartup(e);// Set the access token for ArcGIS Maps SDK for .NET.Esri.ArcGISRuntime.ArcGISRuntimeEnvironment.ApiKey = "YOUR_ACCESS_TOKEN";}}} -
Save and close the
App.xaml.csfile.
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.
-
From the Visual Studio Project menu, choose Add class …. Name the class
ArcGISLoginPrompt.csthen click Add. The new class is added to your project and opens in Visual Studio. -
Select all the code in the new class and delete it.
-
Copy all of the code below and paste it into the
ArcGISLoginPrompt.csclass in your project.ArcGISLoginPrompt.cs// Copyright 2021 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.using Esri.ArcGISRuntime.Portal;using Esri.ArcGISRuntime.Security;using System;using System.Collections.Generic;using System.Threading.Tasks;using System.Windows;using System.Windows.Controls;using System.Windows.Navigation;using System.Windows.Threading;namespace UserAuth{internal static class ArcGISLoginPrompt{private const string ArcGISOnlineUrl = "https://www.arcgis.com/sharing/rest";// Specify the Client ID and Redirect URL to use with OAuth authentication.// See the instructions here for creating OAuth app settings:// https://developers.arcgis.com/documentation/security-and-authentication/user-authentication/tutorials/create-oauth-credentials-user-auth/private const string AppClientId = "YOUR_CLIENT_ID";private const string OAuthRedirectUrl = "YOUR_REDIRECT_URL";public static async Task<bool> EnsureAGOLCredentialAsync(){bool loggedIn = false;try{// Create the portal, prompting the user to log in if they haven't already.var portal = await ArcGISPortal.CreateAsync(new Uri(ArcGISOnlineUrl), loginRequired: true);// If the user logged in successfully, the portal's User property will be non-null.loggedIn = portal.User != null;}catch (OperationCanceledException){// OAuth login was canceled, no need to display error to user.}catch (Exception ex){// Login failureMessageBox.Show("Login failed: " + ex.Message);}return loggedIn;}public static void RegisterOAuthConfig(){var userConfig = new OAuthUserConfiguration(new Uri(ArcGISOnlineUrl), AppClientId, new Uri(OAuthRedirectUrl));AuthenticationManager.Current.OAuthUserConfigurations.Add(userConfig);AuthenticationManager.Current.OAuthAuthorizeHandler = new OAuthAuthorize();}#region OAuth handler// In a desktop (WPF) app, an IOAuthAuthorizeHandler component is used to handle some of the OAuth details. Specifically, it// implements AuthorizeAsync to show the login UI (generated by the server that hosts secure content) in a web control.// When the user logs in successfully, cancels the login, or closes the window without continuing, the IOAuthAuthorizeHandler// is responsible for obtaining the authorization from the server or raising an OperationCanceledException.public class OAuthAuthorize : IOAuthAuthorizeHandler{// Window to contain the OAuth UI.private Window? _authWindow;// Use a TaskCompletionSource to track the completion of the authorization.private TaskCompletionSource<IDictionary<string, string>> _tcs;// URL for the authorization callback result (the redirect URI configured for your application).private string _callbackUrl = "";// URL that handles the OAuth request.private string? _authorizeUrl;// Function to handle authorization requests, takes the URIs for the secured service, the authorization endpoint, and the redirect URI.public Task<IDictionary<string, string>> AuthorizeAsync(Uri serviceUri, Uri authorizeUri, Uri callbackUri){if (_tcs != null && !_tcs.Task.IsCompleted)throw new Exception("Task in progress");_tcs = new TaskCompletionSource<IDictionary<string, string>>();// Store the authorization and redirect URLs._authorizeUrl = authorizeUri.AbsoluteUri;_callbackUrl = callbackUri.AbsoluteUri;// Call a function to show the login controls, make sure it runs on the UI thread for this app.Dispatcher dispatcher = Application.Current.Dispatcher;if (dispatcher == null || dispatcher.CheckAccess()){AuthorizeOnUIThread(_authorizeUrl);}else{Action authorizeOnUIAction = () => AuthorizeOnUIThread(_authorizeUrl);dispatcher.BeginInvoke(authorizeOnUIAction);}// Return the task associated with the TaskCompletionSource.return _tcs.Task;}// Challenge for OAuth credentials on the UI thread.private void AuthorizeOnUIThread(string authorizeUri){// Create a WebBrowser control to display the authorize page.WebBrowser webBrowser = new WebBrowser();// Handle the navigation event for the browser to check for a response to the redirect URL.webBrowser.Navigating += WebBrowserOnNavigating;// Display the web browser in a new window._authWindow = new Window{Content = webBrowser,Width = 450,Height = 450,WindowStartupLocation = WindowStartupLocation.CenterOwner};// Set the app's window as the owner of the browser window (if main window closes, so will the browser).if (Application.Current != null && Application.Current.MainWindow != null){_authWindow.Owner = Application.Current.MainWindow;}// Handle the window closed event then navigate to the authorize url._authWindow.Closed += OnWindowClosed;webBrowser.Navigate(authorizeUri);// Display the window._authWindow.ShowDialog();}// Handle the browser window closing.private void OnWindowClosed(object? sender, EventArgs e){// If the browser window closes, return the focus to the main window.if (_authWindow != null && _authWindow.Owner != null){_authWindow.Owner.Focus();}// If the task wasn't completed, the user must have closed the window without logging in.if (!_tcs.Task.IsCompleted){// Set the task completion source exception to indicate a canceled operation._tcs.SetCanceled();}_authWindow = null;}// Handle browser navigation (content changing).private void WebBrowserOnNavigating(object sender, NavigatingCancelEventArgs e){// Check for a response to the callback url.const string portalApprovalMarker = "/oauth2/approval";WebBrowser? webBrowser = sender as WebBrowser;Uri uri = e.Uri;// If no browser, uri, or an empty url, return.if (webBrowser == null || uri == null || string.IsNullOrEmpty(uri.AbsoluteUri))return;// Check for redirect.bool isRedirected = uri.AbsoluteUri.StartsWith(_callbackUrl) ||_callbackUrl.Contains(portalApprovalMarker) && uri.AbsoluteUri.Contains(portalApprovalMarker);// Check if browser was redirected to the callback URL. (This indicates succesful authentication.)if (isRedirected){e.Cancel = true;// Call a helper function to decode the response parameters.IDictionary<string, string> authResponse = DecodeParameters(uri);// Set the result for the task completion source._tcs.SetResult(authResponse);// Close the window.if (_authWindow != null){_authWindow.Close();}}}private static IDictionary<string, string> DecodeParameters(Uri uri){// Create a dictionary of key value pairs returned in an OAuth authorization response URI query string.string answer = "";// Get the values from the URI fragment or query string.if (!string.IsNullOrEmpty(uri.Fragment)){answer = uri.Fragment.Substring(1);}else{if (!string.IsNullOrEmpty(uri.Query)){answer = uri.Query.Substring(1);}}// Parse parameters into key / value pairs.Dictionary<string, string> keyValueDictionary = new Dictionary<string, string>();string[] keysAndValues = answer.Split(new[] { '&' }, StringSplitOptions.RemoveEmptyEntries);foreach (string kvString in keysAndValues){string[] pair = kvString.Split('=');string key = pair[0];string value = string.Empty;if (key.Length > 1){value = Uri.UnescapeDataString(pair[1]);}keyValueDictionary.Add(key, value);}// Return the dictionary of string keys/values.return keyValueDictionary;}}#endregion OAuth handler}} -
Add your values for the client ID (
AppClientId) and for the redirect URL (OAuthRedirectUrl). These are the user authentication settings you created in the Set up authentication step.ArcGISLoginPrompt.csinternal static class ArcGISLoginPrompt{private const string ArcGISOnlineUrl = "https://www.arcgis.com/sharing/rest";// Specify the Client ID and Redirect URL to use with OAuth authentication.// See the instructions here for creating OAuth app settings:// https://developers.arcgis.com/documentation/security-and-authentication/user-authentication/tutorials/create-oauth-credentials-user-auth/private const string AppClientId = "YOUR_CLIENT_ID";private const string OAuthRedirectUrl = "YOUR_REDIRECT_URL"; -
In the Solution Explorer, expand the node for App.xaml, and double-click App.xaml.cs to open it.
-
In the App class, in the override for the
OnStartup()function, call theSetChallengeHandler()method on your staticArcGISLoginPromptclass.App.xaml.cspublic partial class App : Application{protected override void OnStartup(StartupEventArgs e){base.OnStartup(e);// Call a function to set up the AuthenticationManager for OAuth.UserAuth.ArcGISLoginPrompt.RegisterOAuthConfig();}}} -
Save and close the
App.xaml.csfile.
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.
Add a graphics overlay
A graphics overlay
-
In the Visual Studio > Solution Explorer, double-click MapViewModel.cs to open the file.
The project uses the Model-View-ViewModel (MVVM) design pattern to separate the application logic (view model) from the user interface (view).
MapViewModel.cscontains the view model class for the application, calledMapViewModel. See the Microsoft documentation for more information about the Model-View-ViewModel pattern. -
Add additional required
usingstatements to yourMapViewModelclass.Geocodingcontains classes used for geocoding (finding geographic locations from an address). TheEsri.ArcGISRuntime.UInamespace contains theGraphicsOverlayandGraphicclasses andEsri.ArcGISRuntime.Symbologycontains the classes that define the symbols for displaying them.using System;using System.Collections.Generic;using Esri.ArcGISRuntime.Geometry;using Esri.ArcGISRuntime.Mapping;using System.ComponentModel;using System.Runtime.CompilerServices;using Esri.ArcGISRuntime.Symbology;using Esri.ArcGISRuntime.Tasks.Geocoding;using Esri.ArcGISRuntime.UI;using System.Drawing;using System.Linq;using System.Threading.Tasks; -
In the view model, create a new property named
GraphicsOverlays. This is a collection ofGraphicsOverlaythat will store geocode result graphics (address location and label).45 collapsed lines// Copyright 2021 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.using System;using System.Collections.Generic;using Esri.ArcGISRuntime.Geometry;using Esri.ArcGISRuntime.Mapping;using System.ComponentModel;using System.Runtime.CompilerServices;using Esri.ArcGISRuntime.Symbology;using Esri.ArcGISRuntime.Tasks.Geocoding;using Esri.ArcGISRuntime.UI;using System.Drawing;using System.Linq;using System.Threading.Tasks;namespace SearchForAnAddress{class MapViewModel : INotifyPropertyChanged{public MapViewModel(){SetupMap();}public event PropertyChangedEventHandler? PropertyChanged;protected void OnPropertyChanged([CallerMemberName] string propertyName = ""){var propertyChangedHandler = PropertyChanged;if (propertyChangedHandler != null)propertyChangedHandler(this, new PropertyChangedEventArgs(propertyName));}private Map? _map;public Map? Map{get { return _map; }set{_map = value;OnPropertyChanged();}}private GraphicsOverlayCollection? _graphicsOverlayCollection;public GraphicsOverlayCollection? GraphicsOverlays{get { return _graphicsOverlayCollection; }set{_graphicsOverlayCollection = value;OnPropertyChanged();}}17 collapsed linesprivate void SetupMap(){// Create a new map with a 'topographic vector' basemap.Map map = new Map(BasemapStyle.ArcGISTopographic);// Set the initial viewpoint around the Santa Monica Mountains in California.var mapCenterPoint = new MapPoint(-118.805, 34.027, SpatialReferences.Wgs84);map.InitialViewpoint = new Viewpoint(mapCenterPoint, 100000);// Set the view model "Map" property.this.Map = map;}}} -
At the end of the
SetupMapfunction, add code to create a newGraphicsOverlay, add it to a collection, and assign it to theGraphicsOverlaysproperty.76 collapsed lines// Copyright 2021 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.using System;using System.Collections.Generic;using Esri.ArcGISRuntime.Geometry;using Esri.ArcGISRuntime.Mapping;using System.ComponentModel;using System.Runtime.CompilerServices;using Esri.ArcGISRuntime.Symbology;using Esri.ArcGISRuntime.Tasks.Geocoding;using Esri.ArcGISRuntime.UI;using System.Drawing;using System.Linq;using System.Threading.Tasks;namespace SearchForAnAddress{class MapViewModel : INotifyPropertyChanged{public MapViewModel(){SetupMap();}public event PropertyChangedEventHandler? PropertyChanged;protected void OnPropertyChanged([CallerMemberName] string propertyName = ""){var propertyChangedHandler = PropertyChanged;if (propertyChangedHandler != null)propertyChangedHandler(this, new PropertyChangedEventArgs(propertyName));}private Map? _map;public Map? Map{get { return _map; }set{_map = value;OnPropertyChanged();}}private GraphicsOverlayCollection? _graphicsOverlayCollection;public GraphicsOverlayCollection? GraphicsOverlays{get { return _graphicsOverlayCollection; }set{_graphicsOverlayCollection = value;OnPropertyChanged();}}private void SetupMap(){// Create a new map with a 'topographic vector' basemap.Map map = new Map(BasemapStyle.ArcGISTopographic);// Set the initial viewpoint around the Santa Monica Mountains in California.var mapCenterPoint = new MapPoint(-118.805, 34.027, SpatialReferences.Wgs84);map.InitialViewpoint = new Viewpoint(mapCenterPoint, 100000);// Set the view model "Map" property.this.Map = map;// Set the view model "GraphicsOverlays" property.GraphicsOverlay overlay = new GraphicsOverlay();GraphicsOverlayCollection overlayCollection = new GraphicsOverlayCollection{overlay};this.GraphicsOverlays = overlayCollection;}3 collapsed lines}} -
In the Visual Studio > Solution Explorer, double-click MainWindow.xaml to open the file.
-
Use data binding to bind the
GraphicsOverlaysproperty of theMapViewModelto theMapViewcontrol.Data binding and the Model-View-ViewModel (MVVM) design pattern allow you to separate the logic in your app (the view model) from the presentation layer (the view). Graphics can be added and removed from the graphics overlays in the view model, and those changes appear in the map view through data binding.
15 collapsed lines<Window x:Class="SearchForAnAddress.MainWindow"xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"xmlns:d="http://schemas.microsoft.com/expression/blend/2008"xmlns:mc="http://schemas.openxmlformats.org/markup-compatibility/2006"xmlns:local="clr-namespace:SearchForAnAddress"xmlns:esri="http://schemas.esri.com/arcgis/runtime/2013"mc:Ignorable="d"Title="MainWindow" Height="450" Width="800"><Window.Resources><local:MapViewModel x:Key="MapViewModel" /></Window.Resources><Grid><esri:MapView x:Name="MainMapView"Map="{Binding Map, Source={StaticResource MapViewModel}}"GraphicsOverlays="{Binding GraphicsOverlays, Source={StaticResource MapViewModel}}"/>4 collapsed lines</Grid></Window>
Add a UI for user input
The user will type an address into a text box and then click a button to execute a search. The MapViewModel class contains the logic to execute the search, but the controls are managed by the view.
-
In the Visual Studio > Solution Explorer, double-click MainWindow.xaml to open the file.
-
Add a
Borderabove the map view that contains the address search controls.13 collapsed lines<Window x:Class="SearchForAnAddress.MainWindow"xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"xmlns:d="http://schemas.microsoft.com/expression/blend/2008"xmlns:mc="http://schemas.openxmlformats.org/markup-compatibility/2006"xmlns:local="clr-namespace:SearchForAnAddress"xmlns:esri="http://schemas.esri.com/arcgis/runtime/2013"mc:Ignorable="d"Title="MainWindow" Height="450" Width="800"><Window.Resources><local:MapViewModel x:Key="MapViewModel" /></Window.Resources><Grid><esri:MapView x:Name="MainMapView"Map="{Binding Map, Source={StaticResource MapViewModel}}"GraphicsOverlays="{Binding GraphicsOverlays, Source={StaticResource MapViewModel}}"/><Border Background="LightBlue"HorizontalAlignment="Center" VerticalAlignment="Top"Width="300" Height="60"Margin="0,10"><Grid><Grid.RowDefinitions><RowDefinition Height="20"/><RowDefinition Height="30" /></Grid.RowDefinitions><Grid.ColumnDefinitions><ColumnDefinition Width="3*" /><ColumnDefinition Width="*" /></Grid.ColumnDefinitions><TextBlock Text="Search for an address"Grid.Row="0" Grid.Column="0" Grid.ColumnSpan="2"TextAlignment="Center" VerticalAlignment="Center"FontWeight="SemiBold" /><TextBox x:Name="AddressTextBox"Grid.Row="1" Grid.Column="0"Margin="5"Text="380 New York Street, Redlands CA"/><Button x:Name="SearchAddressButton"Grid.Row="1" Grid.Column="1"Margin="5"Content="Search"Click="SearchAddressButton_Click" /></Grid></Border></Grid>2 collapsed lines</Window>
Create a function to geocode an address
Geocoding is implemented with a locator
-
In the Visual Studio > Solution Explorer, double-click MapViewModel.cs to open the file.
-
Add a new function to search for an address and return its geographic location. The address string and a spatial reference (for output locations) are passed to the function. The function is marked
asyncsince it will make asynchronous calls using theawaitkeyword.76 collapsed lines// Copyright 2021 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.using System;using System.Collections.Generic;using Esri.ArcGISRuntime.Geometry;using Esri.ArcGISRuntime.Mapping;using System.ComponentModel;using System.Runtime.CompilerServices;using Esri.ArcGISRuntime.Symbology;using Esri.ArcGISRuntime.Tasks.Geocoding;using Esri.ArcGISRuntime.UI;using System.Drawing;using System.Linq;using System.Threading.Tasks;namespace SearchForAnAddress{class MapViewModel : INotifyPropertyChanged{public MapViewModel(){SetupMap();}public event PropertyChangedEventHandler? PropertyChanged;protected void OnPropertyChanged([CallerMemberName] string propertyName = ""){var propertyChangedHandler = PropertyChanged;if (propertyChangedHandler != null)propertyChangedHandler(this, new PropertyChangedEventArgs(propertyName));}private Map? _map;public Map? Map{get { return _map; }set{_map = value;OnPropertyChanged();}}private GraphicsOverlayCollection? _graphicsOverlayCollection;public GraphicsOverlayCollection? GraphicsOverlays{get { return _graphicsOverlayCollection; }set{_graphicsOverlayCollection = value;OnPropertyChanged();}}private void SetupMap(){// Create a new map with a 'topographic vector' basemap.Map map = new Map(BasemapStyle.ArcGISTopographic);// Set the initial viewpoint around the Santa Monica Mountains in California.var mapCenterPoint = new MapPoint(-118.805, 34.027, SpatialReferences.Wgs84);map.InitialViewpoint = new Viewpoint(mapCenterPoint, 100000);// Set the view model "Map" property.this.Map = map;// Set the view model "GraphicsOverlays" property.GraphicsOverlay overlay = new GraphicsOverlay();GraphicsOverlayCollection overlayCollection = new GraphicsOverlayCollection{overlay};this.GraphicsOverlays = overlayCollection;}public async Task<MapPoint?> SearchAddress(string address, SpatialReference spatialReference){MapPoint? addressLocation = null;try{}catch (Exception ex){System.Windows.MessageBox.Show("Couldn't find address: " + ex.Message);}// Return the location of the geocode result.return addressLocation;}3 collapsed lines}} -
Get the
GraphicsOverlayand clear all of itsGraphics.89 collapsed lines// Copyright 2021 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.using System;using System.Collections.Generic;using Esri.ArcGISRuntime.Geometry;using Esri.ArcGISRuntime.Mapping;using System.ComponentModel;using System.Runtime.CompilerServices;using Esri.ArcGISRuntime.Symbology;using Esri.ArcGISRuntime.Tasks.Geocoding;using Esri.ArcGISRuntime.UI;using System.Drawing;using System.Linq;using System.Threading.Tasks;namespace SearchForAnAddress{class MapViewModel : INotifyPropertyChanged{public MapViewModel(){SetupMap();}public event PropertyChangedEventHandler? PropertyChanged;protected void OnPropertyChanged([CallerMemberName] string propertyName = ""){var propertyChangedHandler = PropertyChanged;if (propertyChangedHandler != null)propertyChangedHandler(this, new PropertyChangedEventArgs(propertyName));}private Map? _map;public Map? Map{get { return _map; }set{_map = value;OnPropertyChanged();}}private GraphicsOverlayCollection? _graphicsOverlayCollection;public GraphicsOverlayCollection? GraphicsOverlays{get { return _graphicsOverlayCollection; }set{_graphicsOverlayCollection = value;OnPropertyChanged();}}private void SetupMap(){// Create a new map with a 'topographic vector' basemap.Map map = new Map(BasemapStyle.ArcGISTopographic);// Set the initial viewpoint around the Santa Monica Mountains in California.var mapCenterPoint = new MapPoint(-118.805, 34.027, SpatialReferences.Wgs84);map.InitialViewpoint = new Viewpoint(mapCenterPoint, 100000);// Set the view model "Map" property.this.Map = map;// Set the view model "GraphicsOverlays" property.GraphicsOverlay overlay = new GraphicsOverlay();GraphicsOverlayCollection overlayCollection = new GraphicsOverlayCollection{overlay};this.GraphicsOverlays = overlayCollection;}public async Task<MapPoint?> SearchAddress(string address, SpatialReference spatialReference){MapPoint? addressLocation = null;try{// Get the first graphics overlay from the GraphicsOverlays and remove any previous result graphics.GraphicsOverlay? graphicsOverlay = this.GraphicsOverlays?.FirstOrDefault();graphicsOverlay?.Graphics.Clear();13 collapsed lines}catch (Exception ex){System.Windows.MessageBox.Show("Couldn't find address: " + ex.Message);}// Return the location of the geocode result.return addressLocation;}}} -
Create a
LocatorTaskbased on the Geocoding service.A locator task is used to find the location of an address (geocode) or to interpolate an address for a location (reverse geocode). An address includes any type of information that distinguishes a place. A locator
A 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 location.96 collapsed lines// Copyright 2021 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.using System;using System.Collections.Generic;using Esri.ArcGISRuntime.Geometry;using Esri.ArcGISRuntime.Mapping;using System.ComponentModel;using System.Runtime.CompilerServices;using Esri.ArcGISRuntime.Symbology;using Esri.ArcGISRuntime.Tasks.Geocoding;using Esri.ArcGISRuntime.UI;using System.Drawing;using System.Linq;using System.Threading.Tasks;namespace SearchForAnAddress{class MapViewModel : INotifyPropertyChanged{public MapViewModel(){SetupMap();}public event PropertyChangedEventHandler? PropertyChanged;protected void OnPropertyChanged([CallerMemberName] string propertyName = ""){var propertyChangedHandler = PropertyChanged;if (propertyChangedHandler != null)propertyChangedHandler(this, new PropertyChangedEventArgs(propertyName));}private Map? _map;public Map? Map{get { return _map; }set{_map = value;OnPropertyChanged();}}private GraphicsOverlayCollection? _graphicsOverlayCollection;public GraphicsOverlayCollection? GraphicsOverlays{get { return _graphicsOverlayCollection; }set{_graphicsOverlayCollection = value;OnPropertyChanged();}}private void SetupMap(){// Create a new map with a 'topographic vector' basemap.Map map = new Map(BasemapStyle.ArcGISTopographic);// Set the initial viewpoint around the Santa Monica Mountains in California.var mapCenterPoint = new MapPoint(-118.805, 34.027, SpatialReferences.Wgs84);map.InitialViewpoint = new Viewpoint(mapCenterPoint, 100000);// Set the view model "Map" property.this.Map = map;// Set the view model "GraphicsOverlays" property.GraphicsOverlay overlay = new GraphicsOverlay();GraphicsOverlayCollection overlayCollection = new GraphicsOverlayCollection{overlay};this.GraphicsOverlays = overlayCollection;}public async Task<MapPoint?> SearchAddress(string address, SpatialReference spatialReference){MapPoint? addressLocation = null;try{// Get the first graphics overlay from the GraphicsOverlays and remove any previous result graphics.GraphicsOverlay? graphicsOverlay = this.GraphicsOverlays?.FirstOrDefault();graphicsOverlay?.Graphics.Clear();// Create a locator task.LocatorTask locatorTask = new LocatorTask(new Uri("https://geocode-api.arcgis.com/arcgis/rest/services/World/GeocodeServer"));13 collapsed lines}catch (Exception ex){System.Windows.MessageBox.Show("Couldn't find address: " + ex.Message);}// Return the location of the geocode result.return addressLocation;}}} -
Create a new
GeocodeParametersand define some of its properties.- Add the names of attributes to return to the
GeocodeParameters.ResultAttributeNamescollection. An asterisk (*) indicates all attributes. - Set the maximum number of results to be returned with
GeocodeParameters.MaxResults. Results are ordered byscore, so that the first result has the best match score (ranging from 0 for no match to 100 for the best match). - 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. for result locations withGeocodeParameters.OutputSpatialReference. By default, the output spatial reference is defined by the geocode service. For optimal performance when displaying the geocode result, you can ensure that returned coordinates match those of the map view by providing the map view’s 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. Learn more about these parameters in theGeocodeParameters. For a list of attributes returned with geocode results, see Geocoding service output in the ArcGIS services reference.100 collapsed lines// Copyright 2021 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.using System;using System.Collections.Generic;using Esri.ArcGISRuntime.Geometry;using Esri.ArcGISRuntime.Mapping;using System.ComponentModel;using System.Runtime.CompilerServices;using Esri.ArcGISRuntime.Symbology;using Esri.ArcGISRuntime.Tasks.Geocoding;using Esri.ArcGISRuntime.UI;using System.Drawing;using System.Linq;using System.Threading.Tasks;namespace SearchForAnAddress{class MapViewModel : INotifyPropertyChanged{public MapViewModel(){SetupMap();}public event PropertyChangedEventHandler? PropertyChanged;protected void OnPropertyChanged([CallerMemberName] string propertyName = ""){var propertyChangedHandler = PropertyChanged;if (propertyChangedHandler != null)propertyChangedHandler(this, new PropertyChangedEventArgs(propertyName));}private Map? _map;public Map? Map{get { return _map; }set{_map = value;OnPropertyChanged();}}private GraphicsOverlayCollection? _graphicsOverlayCollection;public GraphicsOverlayCollection? GraphicsOverlays{get { return _graphicsOverlayCollection; }set{_graphicsOverlayCollection = value;OnPropertyChanged();}}private void SetupMap(){// Create a new map with a 'topographic vector' basemap.Map map = new Map(BasemapStyle.ArcGISTopographic);// Set the initial viewpoint around the Santa Monica Mountains in California.var mapCenterPoint = new MapPoint(-118.805, 34.027, SpatialReferences.Wgs84);map.InitialViewpoint = new Viewpoint(mapCenterPoint, 100000);// Set the view model "Map" property.this.Map = map;// Set the view model "GraphicsOverlays" property.GraphicsOverlay overlay = new GraphicsOverlay();GraphicsOverlayCollection overlayCollection = new GraphicsOverlayCollection{overlay};this.GraphicsOverlays = overlayCollection;}public async Task<MapPoint?> SearchAddress(string address, SpatialReference spatialReference){MapPoint? addressLocation = null;try{// Get the first graphics overlay from the GraphicsOverlays and remove any previous result graphics.GraphicsOverlay? graphicsOverlay = this.GraphicsOverlays?.FirstOrDefault();graphicsOverlay?.Graphics.Clear();// Create a locator task.LocatorTask locatorTask = new LocatorTask(new Uri("https://geocode-api.arcgis.com/arcgis/rest/services/World/GeocodeServer"));// Define geocode parameters: limit the results to one and get all attributes.GeocodeParameters geocodeParameters = new GeocodeParameters();geocodeParameters.ResultAttributeNames.Add("*");geocodeParameters.MaxResults = 1;geocodeParameters.OutputSpatialReference = spatialReference;13 collapsed lines}catch (Exception ex){System.Windows.MessageBox.Show("Couldn't find address: " + ex.Message);}// Return the location of the geocode result.return addressLocation;}}} - Add the names of attributes to return to the
-
To find the location for the provided address, call
LocatorTask.GeocodeAsync, providing theaddressstring andgeocodeParameters. The result is a read-only list ofGeocodeResultobjects. In this tutorial, either one or zero results will be returned, as the maximum results parameter was set to 1.103 collapsed lines// Copyright 2021 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.using System;using System.Collections.Generic;using Esri.ArcGISRuntime.Geometry;using Esri.ArcGISRuntime.Mapping;using System.ComponentModel;using System.Runtime.CompilerServices;using Esri.ArcGISRuntime.Symbology;using Esri.ArcGISRuntime.Tasks.Geocoding;using Esri.ArcGISRuntime.UI;using System.Drawing;using System.Linq;using System.Threading.Tasks;namespace SearchForAnAddress{class MapViewModel : INotifyPropertyChanged{public MapViewModel(){SetupMap();}public event PropertyChangedEventHandler? PropertyChanged;protected void OnPropertyChanged([CallerMemberName] string propertyName = ""){var propertyChangedHandler = PropertyChanged;if (propertyChangedHandler != null)propertyChangedHandler(this, new PropertyChangedEventArgs(propertyName));}private Map? _map;public Map? Map{get { return _map; }set{_map = value;OnPropertyChanged();}}private GraphicsOverlayCollection? _graphicsOverlayCollection;public GraphicsOverlayCollection? GraphicsOverlays{get { return _graphicsOverlayCollection; }set{_graphicsOverlayCollection = value;OnPropertyChanged();}}private void SetupMap(){// Create a new map with a 'topographic vector' basemap.Map map = new Map(BasemapStyle.ArcGISTopographic);// Set the initial viewpoint around the Santa Monica Mountains in California.var mapCenterPoint = new MapPoint(-118.805, 34.027, SpatialReferences.Wgs84);map.InitialViewpoint = new Viewpoint(mapCenterPoint, 100000);// Set the view model "Map" property.this.Map = map;// Set the view model "GraphicsOverlays" property.GraphicsOverlay overlay = new GraphicsOverlay();GraphicsOverlayCollection overlayCollection = new GraphicsOverlayCollection{overlay};this.GraphicsOverlays = overlayCollection;}public async Task<MapPoint?> SearchAddress(string address, SpatialReference spatialReference){MapPoint? addressLocation = null;try{// Get the first graphics overlay from the GraphicsOverlays and remove any previous result graphics.GraphicsOverlay? graphicsOverlay = this.GraphicsOverlays?.FirstOrDefault();graphicsOverlay?.Graphics.Clear();// Create a locator task.LocatorTask locatorTask = new LocatorTask(new Uri("https://geocode-api.arcgis.com/arcgis/rest/services/World/GeocodeServer"));// Define geocode parameters: limit the results to one and get all attributes.GeocodeParameters geocodeParameters = new GeocodeParameters();geocodeParameters.ResultAttributeNames.Add("*");geocodeParameters.MaxResults = 1;geocodeParameters.OutputSpatialReference = spatialReference;// Geocode the address string and get the first (only) result.IReadOnlyList<GeocodeResult> results = await locatorTask.GeocodeAsync(address, geocodeParameters);GeocodeResult? geocodeResult = results[0];if(geocodeResult == null) { throw new Exception("No matches found."); }13 collapsed lines}catch (Exception ex){System.Windows.MessageBox.Show("Couldn't find address: " + ex.Message);}// Return the location of the geocode result.return addressLocation;}}}
Display the result
The geocode result can be displayed by adding a graphic
-
If a result was found, create two
Graphicobjects and add them to thegraphicsOverlay. Create a graphic to display the geocode result’s location, and another to show the geocode result’s label text (the located address).109 collapsed lines// Copyright 2021 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.using System;using System.Collections.Generic;using Esri.ArcGISRuntime.Geometry;using Esri.ArcGISRuntime.Mapping;using System.ComponentModel;using System.Runtime.CompilerServices;using Esri.ArcGISRuntime.Symbology;using Esri.ArcGISRuntime.Tasks.Geocoding;using Esri.ArcGISRuntime.UI;using System.Drawing;using System.Linq;using System.Threading.Tasks;namespace SearchForAnAddress{class MapViewModel : INotifyPropertyChanged{public MapViewModel(){SetupMap();}public event PropertyChangedEventHandler? PropertyChanged;protected void OnPropertyChanged([CallerMemberName] string propertyName = ""){var propertyChangedHandler = PropertyChanged;if (propertyChangedHandler != null)propertyChangedHandler(this, new PropertyChangedEventArgs(propertyName));}private Map? _map;public Map? Map{get { return _map; }set{_map = value;OnPropertyChanged();}}private GraphicsOverlayCollection? _graphicsOverlayCollection;public GraphicsOverlayCollection? GraphicsOverlays{get { return _graphicsOverlayCollection; }set{_graphicsOverlayCollection = value;OnPropertyChanged();}}private void SetupMap(){// Create a new map with a 'topographic vector' basemap.Map map = new Map(BasemapStyle.ArcGISTopographic);// Set the initial viewpoint around the Santa Monica Mountains in California.var mapCenterPoint = new MapPoint(-118.805, 34.027, SpatialReferences.Wgs84);map.InitialViewpoint = new Viewpoint(mapCenterPoint, 100000);// Set the view model "Map" property.this.Map = map;// Set the view model "GraphicsOverlays" property.GraphicsOverlay overlay = new GraphicsOverlay();GraphicsOverlayCollection overlayCollection = new GraphicsOverlayCollection{overlay};this.GraphicsOverlays = overlayCollection;}public async Task<MapPoint?> SearchAddress(string address, SpatialReference spatialReference){MapPoint? addressLocation = null;try{// Get the first graphics overlay from the GraphicsOverlays and remove any previous result graphics.GraphicsOverlay? graphicsOverlay = this.GraphicsOverlays?.FirstOrDefault();graphicsOverlay?.Graphics.Clear();// Create a locator task.LocatorTask locatorTask = new LocatorTask(new Uri("https://geocode-api.arcgis.com/arcgis/rest/services/World/GeocodeServer"));// Define geocode parameters: limit the results to one and get all attributes.GeocodeParameters geocodeParameters = new GeocodeParameters();geocodeParameters.ResultAttributeNames.Add("*");geocodeParameters.MaxResults = 1;geocodeParameters.OutputSpatialReference = spatialReference;// Geocode the address string and get the first (only) result.IReadOnlyList<GeocodeResult> results = await locatorTask.GeocodeAsync(address, geocodeParameters);GeocodeResult? geocodeResult = results[0];if(geocodeResult == null) { throw new Exception("No matches found."); }// Create a graphic to display the result location.SimpleMarkerSymbol markerSymbol = new SimpleMarkerSymbol(SimpleMarkerSymbolStyle.Square, Color.Blue, 12);Graphic markerGraphic = new Graphic(geocodeResult.DisplayLocation, geocodeResult.Attributes, markerSymbol);// Create a graphic to display the result address label.TextSymbol textSymbol = new TextSymbol(geocodeResult.Label, Color.Red, 18, HorizontalAlignment.Center, VerticalAlignment.Bottom);Graphic textGraphic = new Graphic(geocodeResult.DisplayLocation, textSymbol);// Add the location and label graphics to the graphics overlay.graphicsOverlay?.Graphics.Add(markerGraphic);graphicsOverlay?.Graphics.Add(textGraphic);13 collapsed lines}catch (Exception ex){System.Windows.MessageBox.Show("Couldn't find address: " + ex.Message);}// Return the location of the geocode result.return addressLocation;}}} -
Set
addressLocationwith the location of the result to return it from the function. The calling function will use thisMapPointto pan the display to the result location.122 collapsed lines// Copyright 2021 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.using System;using System.Collections.Generic;using Esri.ArcGISRuntime.Geometry;using Esri.ArcGISRuntime.Mapping;using System.ComponentModel;using System.Runtime.CompilerServices;using Esri.ArcGISRuntime.Symbology;using Esri.ArcGISRuntime.Tasks.Geocoding;using Esri.ArcGISRuntime.UI;using System.Drawing;using System.Linq;using System.Threading.Tasks;namespace SearchForAnAddress{class MapViewModel : INotifyPropertyChanged{public MapViewModel(){SetupMap();}public event PropertyChangedEventHandler? PropertyChanged;protected void OnPropertyChanged([CallerMemberName] string propertyName = ""){var propertyChangedHandler = PropertyChanged;if (propertyChangedHandler != null)propertyChangedHandler(this, new PropertyChangedEventArgs(propertyName));}private Map? _map;public Map? Map{get { return _map; }set{_map = value;OnPropertyChanged();}}private GraphicsOverlayCollection? _graphicsOverlayCollection;public GraphicsOverlayCollection? GraphicsOverlays{get { return _graphicsOverlayCollection; }set{_graphicsOverlayCollection = value;OnPropertyChanged();}}private void SetupMap(){// Create a new map with a 'topographic vector' basemap.Map map = new Map(BasemapStyle.ArcGISTopographic);// Set the initial viewpoint around the Santa Monica Mountains in California.var mapCenterPoint = new MapPoint(-118.805, 34.027, SpatialReferences.Wgs84);map.InitialViewpoint = new Viewpoint(mapCenterPoint, 100000);// Set the view model "Map" property.this.Map = map;// Set the view model "GraphicsOverlays" property.GraphicsOverlay overlay = new GraphicsOverlay();GraphicsOverlayCollection overlayCollection = new GraphicsOverlayCollection{overlay};this.GraphicsOverlays = overlayCollection;}public async Task<MapPoint?> SearchAddress(string address, SpatialReference spatialReference){MapPoint? addressLocation = null;try{// Get the first graphics overlay from the GraphicsOverlays and remove any previous result graphics.GraphicsOverlay? graphicsOverlay = this.GraphicsOverlays?.FirstOrDefault();graphicsOverlay?.Graphics.Clear();// Create a locator task.LocatorTask locatorTask = new LocatorTask(new Uri("https://geocode-api.arcgis.com/arcgis/rest/services/World/GeocodeServer"));// Define geocode parameters: limit the results to one and get all attributes.GeocodeParameters geocodeParameters = new GeocodeParameters();geocodeParameters.ResultAttributeNames.Add("*");geocodeParameters.MaxResults = 1;geocodeParameters.OutputSpatialReference = spatialReference;// Geocode the address string and get the first (only) result.IReadOnlyList<GeocodeResult> results = await locatorTask.GeocodeAsync(address, geocodeParameters);GeocodeResult? geocodeResult = results[0];if(geocodeResult == null) { throw new Exception("No matches found."); }// Create a graphic to display the result location.SimpleMarkerSymbol markerSymbol = new SimpleMarkerSymbol(SimpleMarkerSymbolStyle.Square, Color.Blue, 12);Graphic markerGraphic = new Graphic(geocodeResult.DisplayLocation, geocodeResult.Attributes, markerSymbol);// Create a graphic to display the result address label.TextSymbol textSymbol = new TextSymbol(geocodeResult.Label, Color.Red, 18, HorizontalAlignment.Center, VerticalAlignment.Bottom);Graphic textGraphic = new Graphic(geocodeResult.DisplayLocation, textSymbol);// Add the location and label graphics to the graphics overlay.graphicsOverlay?.Graphics.Add(markerGraphic);graphicsOverlay?.Graphics.Add(textGraphic);// Set the address location to return from the function.addressLocation = geocodeResult?.DisplayLocation;13 collapsed lines}catch (Exception ex){System.Windows.MessageBox.Show("Couldn't find address: " + ex.Message);}// Return the location of the geocode result.return addressLocation;}}}
Search for an address when the button is clicked
-
In the Visual Studio > Solution Explorer, double-click MainWindow.xaml.cs to open the file.
A view defined with XAML, such as
MainWindow, is composed of two files in a Visual Studio project. The visual elements (such as map views, buttons, text boxes, and so on) are defined with XAML markup in a.xamlfile. This file is often referred to as the “page”. The code for the XAML elements is stored in an associated.xaml.csfile that is known as the “code-behind”, since it stores the code behind the controls.It’s not uncommon in an MVVM implementation to have a limited amount of code that responds to control events in the code behind. A more pure MVVM approach, however, is to have the view model handle UI interaction using commands and behaviors. For the sake of simplicity, you’ll handle the button click event in the code behind.
-
Add a handler for the
SearchAddressButtonclick event.Asynchronous functions should return
TaskorTask<T>. For event handlers, such as theButton.Clickhandler, the function must returnvoidto conform to the delegate signature. See the Microsoft documentation regarding Async return types.37 collapsed lines// Copyright 2021 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.using Esri.ArcGISRuntime.Geometry;using System;using System.Collections.Generic;using System.Linq;using System.Text;using System.Threading.Tasks;using System.Windows;using System.Windows.Controls;using System.Windows.Data;using System.Windows.Documents;using System.Windows.Input;using System.Windows.Media;using System.Windows.Media.Imaging;using System.Windows.Navigation;using System.Windows.Shapes;namespace SearchForAnAddress{/// <summary>/// Interaction logic for MainWindow.xaml/// </summary>public partial class MainWindow : Window{public MainWindow(){InitializeComponent();}private async void SearchAddressButton_Click(object sender, RoutedEventArgs e){}3 collapsed lines}} -
Find
MapViewModelfrom the page resources.42 collapsed lines// Copyright 2021 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.using Esri.ArcGISRuntime.Geometry;using System;using System.Collections.Generic;using System.Linq;using System.Text;using System.Threading.Tasks;using System.Windows;using System.Windows.Controls;using System.Windows.Data;using System.Windows.Documents;using System.Windows.Input;using System.Windows.Media;using System.Windows.Media.Imaging;using System.Windows.Navigation;using System.Windows.Shapes;namespace SearchForAnAddress{/// <summary>/// Interaction logic for MainWindow.xaml/// </summary>public partial class MainWindow : Window{public MainWindow(){InitializeComponent();}private async void SearchAddressButton_Click(object sender, RoutedEventArgs e){// Get the MapViewModel from the page (defined as a static resource).var viewModel = (MapViewModel)FindResource("MapViewModel");if(viewModel == null) { return; }}3 collapsed lines}} -
Call the
SearchAddressfunction on theMapViewModeland store the returnedMapPoint.42 collapsed lines// Copyright 2021 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.using Esri.ArcGISRuntime.Geometry;using System;using System.Collections.Generic;using System.Linq;using System.Text;using System.Threading.Tasks;using System.Windows;using System.Windows.Controls;using System.Windows.Data;using System.Windows.Documents;using System.Windows.Input;using System.Windows.Media;using System.Windows.Media.Imaging;using System.Windows.Navigation;using System.Windows.Shapes;namespace SearchForAnAddress{/// <summary>/// Interaction logic for MainWindow.xaml/// </summary>public partial class MainWindow : Window{public MainWindow(){InitializeComponent();}private async void SearchAddressButton_Click(object sender, RoutedEventArgs e){// Get the MapViewModel from the page (defined as a static resource).var viewModel = (MapViewModel)FindResource("MapViewModel");if(viewModel == null) { return; }// Call SearchAddress on the view model, pass the address text and the map view's spatial reference.var spatialReference = MainMapView.SpatialReference;if(spatialReference== null) { return; }MapPoint? addressPoint = await viewModel.SearchAddress(AddressTextBox.Text, spatialReference);}3 collapsed lines}} -
If a map point is returned, center the
MapViewon the address result.42 collapsed lines// Copyright 2021 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.using Esri.ArcGISRuntime.Geometry;using System;using System.Collections.Generic;using System.Linq;using System.Text;using System.Threading.Tasks;using System.Windows;using System.Windows.Controls;using System.Windows.Data;using System.Windows.Documents;using System.Windows.Input;using System.Windows.Media;using System.Windows.Media.Imaging;using System.Windows.Navigation;using System.Windows.Shapes;namespace SearchForAnAddress{/// <summary>/// Interaction logic for MainWindow.xaml/// </summary>public partial class MainWindow : Window{public MainWindow(){InitializeComponent();}private async void SearchAddressButton_Click(object sender, RoutedEventArgs e){// Get the MapViewModel from the page (defined as a static resource).var viewModel = (MapViewModel)FindResource("MapViewModel");if(viewModel == null) { return; }// Call SearchAddress on the view model, pass the address text and the map view's spatial reference.var spatialReference = MainMapView.SpatialReference;if(spatialReference== null) { return; }MapPoint? addressPoint = await viewModel.SearchAddress(AddressTextBox.Text, spatialReference);// If a result was found, center the display on it.if (addressPoint != null){await MainMapView.SetViewpointCenterAsync(addressPoint);}}3 collapsed lines}} -
Click Debug > Start Debugging (or press <F5> on the keyboard) to run the app. If your app uses user authentication, enter your ArcGIS Online credentials when prompted.
You will see the address search controls at the top center of the map. To search for an address, enter an address and then click Search. If a result is found, the map will pan to the location and label a graphic for that address.
Alternatively, you can download the tutorial solution, as follows.
Option 2: Download the solution
-
Click the Download solution link in the right-hand panel of the page.
-
Unzip the file to a location on your machine.
-
Open the
.slnfile in Visual Studio.
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
-
In Visual Studio, in the Solution Explorer, click App.xaml.cs to open the file.
-
Set the
ArcGISEnvironment.ApiKeyproperty with your API key access token.App.xaml.csprotected override void OnStartup(StartupEventArgs e){base.OnStartup(e);// Set the access token for ArcGIS Maps SDK for .NET.Esri.ArcGISRuntime.ArcGISRuntimeEnvironment.ApiKey = "YOUR_ACCESS_TOKEN";// Call a function to set up the AuthenticationManager for OAuth.UserAuth.ArcGISLoginPrompt.RegisterOAuthConfig();} -
Remove the code that sets up user authentication.
App.xaml.csprotected override void OnStartup(StartupEventArgs e){base.OnStartup(e);// Set the access token for ArcGIS Maps SDK for .NET.Esri.ArcGISRuntime.ArcGISRuntimeEnvironment.ApiKey = "YOUR_ACCESS_TOKEN";// Call a function to set up the AuthenticationManager for OAuth.UserAuth.ArcGISLoginPrompt.RegisterOAuthConfig();}
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.
-
From the Visual Studio Solution explorer window, open the
ArcGISLoginPrompt.csfile. -
Set your values for the client ID (
OAuthClientID) and the redirect URL (OAuthRedirectUrl). These are the user authentication settings you created in the Set up authentication step.ArcGISLoginPrompt.csinternal static class ArcGISLoginPrompt{private const string ArcGISOnlineUrl = "https://www.arcgis.com/sharing/rest";// Specify the Client ID and Redirect URL to use with OAuth authentication.// See the instructions here for creating OAuth app settings:// https://developers.arcgis.com/documentation/security-and-authentication/user-authentication/tutorials/create-oauth-credentials-user-auth/private const string AppClientId = "YOUR_CLIENT_ID";private const string OAuthRedirectUrl = "YOUR_REDIRECT_URL"; -
In Visual Studio, in the Solution Explorer, click App.xaml.cs to open the file.
-
Remove the line of code that sets an API key access token.
App.xaml.csprotected override void OnStartup(StartupEventArgs e){base.OnStartup(e);// Set the access token for ArcGIS Maps SDK for .NET.Esri.ArcGISRuntime.ArcGISRuntimeEnvironment.ApiKey = "YOUR_ACCESS_TOKEN";// Call a function to set up the AuthenticationManager for OAuth.UserAuth.ArcGISLoginPrompt.RegisterOAuthConfig();}
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
Click Debug > Start Debugging (or press <F5> on the keyboard) to run the app. If your app uses user authentication, enter your ArcGIS Online credentials when prompted.
You will see the address search controls at the top center of the map. To search for an address, enter an address and then click Search. If a result is found, the map will pan to the location and label a graphic for that address.
What’s next?
Learn how to use additional API features, ArcGIS location services, and ArcGIS tools in these tutorials: