Click or drag to resize

LocatorTask Class

Represents a task that enables geocoding and reverse geocoding against an ArcGIS locator.
Inheritance Hierarchy
SystemObject
  Esri.ArcGISRuntime.Tasks.GeocodingLocatorTask

Namespace:  Esri.ArcGISRuntime.Tasks.Geocoding
Assembly:  Esri.ArcGISRuntime (in Esri.ArcGISRuntime.dll) Version: 100.11.0
Syntax
public sealed class LocatorTask : ILoadable, 
	IDisposable, IApiKeyResource

The LocatorTask type exposes the following members.

Constructors
  NameDescription
Public methodLocatorTask
Initializes a new instance of the LocatorTask class
Top
Properties
  NameDescription
Public propertyApiKey
Gets or sets the unique key generated from ArcGIS Developers website.
Public propertyCredential
Gets or sets the security credential used to access the locator web service
Public propertyLoadError
Gets the Exception associated with the last load error.
Public propertyLoadStatus
Gets the load status.
Public propertyLocatorInfo
Gets the locator's metadata.
Public propertyUri
Gets the URI of the locator.
Top
Methods
  NameDescription
Public methodCancelLoad
Cancel loading metadata for the object.
Public methodStatic memberCode exampleCreateAsync
Creates a new instance of the LocatorTask class
Public methodDispose
Performs application-defined tasks associated with freeing, releasing, or resetting unmanaged resources.
Public methodGeocodeAsync(DictionaryString, String)
Executes a geocoding operation to find location candidates for a given multiline address.
Public methodCode exampleGeocodeAsync(String)
Executes a geocoding operation to find location candidates for a given address.
Public methodGeocodeAsync(SuggestResult)
Executes a geocoding operation to find location candidates for a given address suggestion.
Public methodGeocodeAsync(DictionaryString, String, GeocodeParameters)
Executes a geocoding operation to find location candidates for a given multiline address and set of search parameters.
Public methodGeocodeAsync(DictionaryString, String, CancellationToken)
Executes a geocoding operation to find location candidates for a given multiline address.
Public methodCode exampleGeocodeAsync(String, GeocodeParameters)
Executes a geocoding operation to find location candidates for a given address and set of search parameters.
Public methodGeocodeAsync(String, CancellationToken)
Executes a geocoding operation to find location candidates for a given address.
Public methodGeocodeAsync(SuggestResult, GeocodeParameters)
Executes a geocoding operation to find location candidates for a given address suggestion and set of search parameters.
Public methodGeocodeAsync(SuggestResult, CancellationToken)
Executes a geocoding operation to find location candidates for a given address suggestion.
Public methodGeocodeAsync(DictionaryString, String, GeocodeParameters, CancellationToken)
Executes a geocoding operation to find location candidates for a given multiline address and set of search parameters.
Public methodGeocodeAsync(String, GeocodeParameters, CancellationToken)
Executes a geocoding operation to find location candidates for a given address and set of search parameters.
Public methodGeocodeAsync(SuggestResult, GeocodeParameters, CancellationToken)
Executes a geocoding operation to find location candidates for a given address suggestion and set of search parameters.
Public methodLoadAsync
Load the metadata for the object asynchronously.
Public methodRetryLoadAsync
Loads or retries loading metadata for the object asynchronously.
Public methodCode exampleReverseGeocodeAsync(MapPoint)
Executes a reverse geocoding operation to find address candidates for a given location.
Public methodCode exampleReverseGeocodeAsync(MapPoint, ReverseGeocodeParameters)
Executes a reverse geocoding operation to find address candidates for a given location and set of search parameters.
Public methodReverseGeocodeAsync(MapPoint, CancellationToken)
Executes a reverse geocoding operation to find address candidates for a given location.
Public methodReverseGeocodeAsync(MapPoint, ReverseGeocodeParameters, CancellationToken)
Executes a reverse geocoding operation to find address candidates for a given location and set of search parameters.
Public methodCode exampleSuggestAsync(String)
Retrieves a list of possible address variants for a given partial address.
Public methodCode exampleSuggestAsync(String, SuggestParameters)
Retrieves a list of possible address variants for a given partial address and set of search parameters.
Public methodSuggestAsync(String, CancellationToken)
Retrieves a list of possible address variants for a given partial address and set of search parameters.
Public methodSuggestAsync(String, SuggestParameters, CancellationToken)
Retrieves a list of possible address variants for a given partial address and set of search parameters.
Top
Events
  NameDescription
Public eventLoaded
Event that is raised when the object is done loading.
Public eventLoadStatusChanged
Event that is raised when the LoadStatus property changes.
Top
Remarks
Geocoding is the process of assigning a location, usually in the form of coordinate values (points), to an address by comparing the descriptive location elements in the address to those present in the reference material. Addresses come in many forms, ranging from the common address format of a house number followed by the street name and succeeding information to other location descriptions such as postal zone or census tract. An address includes any type of information that distinguishes a place. Reverse geocoding is the process of determining the closest address to a location usually given in the form of a coordinate value (point).
Examples

WPF

Example Name: FindAddress

Find the location for an address.

Code example screen shot.

C#
// Copyright 2017 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 System;
using System.Collections.Generic;
using System.IO;
using System.Linq;
using System.Reflection;
using System.Threading.Tasks;
using System.Windows;
using System.Windows.Controls;
using Esri.ArcGISRuntime.Data;
using Esri.ArcGISRuntime.Geometry;
using Esri.ArcGISRuntime.Mapping;
using Esri.ArcGISRuntime.Symbology;
using Esri.ArcGISRuntime.Tasks.Geocoding;
using Esri.ArcGISRuntime.UI;
using Esri.ArcGISRuntime.UI.Controls;

namespace ArcGISRuntime.WPF.Samples.FindAddress
{
    [ArcGISRuntime.Samples.Shared.Attributes.Sample(
        name: "Find address",
        category: "Search",
        description: "Find the location for an address.",
        instructions: "For simplicity, the sample comes loaded with a set of suggested addresses. Choose an address from the suggestions or submit your own address to show its location on the map in a callout.",
        tags: new[] { "address", "geocode", "locator", "search" })]
    [ArcGISRuntime.Samples.Shared.Attributes.EmbeddedResource(@"PictureMarkerSymbols\pin_star_blue.png")]
    public partial class FindAddress
    {
        // Addresses for suggestion.
        private readonly string[] _addresses =
        {
            "277 N Avenida Caballeros, Palm Springs, CA",
            "380 New York St, Redlands, CA 92373",
            "Београд",
            "Москва",
            "北京"
        };

        // The LocatorTask provides geocoding services
        private LocatorTask _geocoder;

        // Service Uri to be provided to the LocatorTask (geocoder)
        private Uri _serviceUri = new Uri("https://geocode.arcgis.com/arcgis/rest/services/World/GeocodeServer");

        public FindAddress()
        {
            InitializeComponent();

            // Setup the control references and execute initialization
            Initialize();
        }

        private async void Initialize()
        {
            // Create new Map with basemap
            Map myMap = new Map(BasemapStyle.ArcGISImagery);

            // Provide used Map to the MapView
            MyMapView.Map = myMap;

            // Set addresses as items source
            SearchBox.ItemsSource = _addresses;

            // Enable tap-for-info pattern on results
            MyMapView.GeoViewTapped += MyMapView_GeoViewTapped;

            // Initialize the LocatorTask with the provided service Uri
            try
            {
                _geocoder = await LocatorTask.CreateAsync(_serviceUri);

                // Enable UI controls now that the LocatorTask is ready
                SearchBox.IsEnabled = true;
                SearchButton.IsEnabled = true;
            }
            catch (Exception e)
            {
                MessageBox.Show(e.ToString(), "Error");
            }
        }

        private async void UpdateSearch()
        {
            // Get the text in the search bar
            string enteredText = SearchBox.Text;

            // Clear existing marker
            MyMapView.GraphicsOverlays.Clear();

            // Return gracefully if the textbox is empty or the geocoder isn't ready
            if (String.IsNullOrWhiteSpace(enteredText) || _geocoder == null) { return; }

            try
            {
                // Get suggestions based on the input text
                IReadOnlyList<SuggestResult> suggestions = await _geocoder.SuggestAsync(enteredText);

                // Stop gracefully if there are no suggestions
                if (suggestions.Count < 1) { return; }

                // Get the full address for the first suggestion
                SuggestResult firstSuggestion = suggestions.First();
                IReadOnlyList<GeocodeResult> addresses = await _geocoder.GeocodeAsync(firstSuggestion.Label);

                // Stop gracefully if the geocoder does not return a result
                if (addresses.Count < 1) { return; }

                // Place a marker on the map - 1. Create the overlay
                GraphicsOverlay resultOverlay = new GraphicsOverlay();
                // 2. Get the Graphic to display
                Graphic point = await GraphicForPoint(addresses.First().DisplayLocation);
                // 3. Add the Graphic to the GraphicsOverlay
                resultOverlay.Graphics.Add(point);
                // 4. Add the GraphicsOverlay to the MapView
                MyMapView.GraphicsOverlays.Add(resultOverlay);

                // Update the map extent to show the marker
                MyMapView.SetViewpoint(new Viewpoint(addresses.First().Extent));
            }
            catch (Exception e)
            {
                MessageBox.Show(e.ToString(), "Error");
            }
        }

        /// <summary>
        /// Creates and returns a Graphic associated with the given MapPoint
        /// </summary>
        private async Task<Graphic> GraphicForPoint(MapPoint point)
        {
            // Get current assembly that contains the image
            Assembly currentAssembly = Assembly.GetExecutingAssembly();

            // Get image as a stream from the resources
            // Picture is defined as EmbeddedResource and DoNotCopy
            Stream resourceStream = currentAssembly.GetManifestResourceStream(
                "ArcGISRuntime.Resources.PictureMarkerSymbols.pin_star_blue.png");

            // Create new symbol using asynchronous factory method from stream
            PictureMarkerSymbol pinSymbol = await PictureMarkerSymbol.CreateAsync(resourceStream);
            pinSymbol.Width = 60;
            pinSymbol.Height = 60;
            // The image is a pin; offset the image so that the pinpoint
            //     is on the point rather than the image's true center
            pinSymbol.LeaderOffsetX = 30;
            pinSymbol.OffsetY = 14;
            return new Graphic(point, pinSymbol);
        }

        private void OnSuggestionChosen(object sender, SelectionChangedEventArgs e)
        {
            // Return if the user is typing.
            if (SearchBox.SelectedValue == null)
            {
                return;
            }

            // Update the search
            SearchBox.Text = SearchBox.SelectedValue.ToString();
            UpdateSearch();
        }

        private void Button_Click(object sender, System.Windows.RoutedEventArgs e)
        {
            UpdateSearch();
        }

        /// <summary>
        /// Handle tap event on the map; displays callouts showing the address for a tapped search result
        /// </summary>
        private async void MyMapView_GeoViewTapped(object sender, GeoViewInputEventArgs e)
        {
            try
            {
                // Search for the graphics underneath the user's tap
                IReadOnlyList<IdentifyGraphicsOverlayResult> results = await MyMapView.IdentifyGraphicsOverlaysAsync(e.Position, 12, false);

                // Return gracefully if there was no result
                if (results.Count < 1 || results.First().Graphics.Count < 1) { return; }

                // Reverse geocode to get addresses
                IReadOnlyList<GeocodeResult> addresses = await _geocoder.ReverseGeocodeAsync(e.Location);

                // Get the first result
                GeocodeResult address = addresses.First();
                // Use the city and region for the Callout Title
                string calloutTitle = address.Attributes["City"] + ", " + address.Attributes["Region"];
                // Use the metro area for the Callout Detail
                string calloutDetail = address.Attributes["MetroArea"].ToString();

                // Define the callout
                CalloutDefinition calloutBody = new CalloutDefinition(calloutTitle, calloutDetail);

                // Show the callout on the map at the tapped location
                MyMapView.ShowCalloutAt(e.Location, calloutBody);
            }
            catch (Exception ex)
            {
                MessageBox.Show(ex.ToString(), "Error");
            }
        }
    }
}
XAML
<UserControl x:Class="ArcGISRuntime.WPF.Samples.FindAddress.FindAddress"
             xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
             xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
             xmlns:esri="http://schemas.esri.com/arcgis/runtime/2013">
    <Grid>
        <esri:MapView x:Name="MyMapView" />
        <Border Style="{StaticResource BorderStyle}">
            <Grid>
                <Grid.RowDefinitions>
                    <RowDefinition />
                    <RowDefinition />
                </Grid.RowDefinitions>
                <Grid.ColumnDefinitions>
                    <ColumnDefinition Width="2*" />
                    <ColumnDefinition Width="*" />
                </Grid.ColumnDefinitions>
                <TextBlock Text="Enter an address to search or select from a preset option."
                           Grid.Row="0" Grid.Column="0" Grid.ColumnSpan="2"
                           TextAlignment="Center"
                           FontWeight="SemiBold" />
                <ComboBox x:Name="SearchBox"
                          Grid.Row="1" Grid.Column="0"
                          Margin="0,5,5,0"
                          IsEnabled="False" IsEditable="True"
                          SelectionChanged="OnSuggestionChosen" />
                <Button x:Name="SearchButton"
                        Grid.Row="1" Grid.Column="1"
                        Margin="0,5,0,0"
                        Content="Search" IsEnabled="False"
                        Click="Button_Click" />
            </Grid>
        </Border>
    </Grid>
</UserControl>
See Also
Additional Examples
Hyperlink to ExampleDescription
FindAddressFind the location for an address.
FindPlaceFind places of interest near a location or within a specific area.
MobileMapSearchAndRouteDisplay maps and use locators to enable search and routing offline using a Mobile Map Package.
OfflineGeocodeGeocode addresses to locations and reverse geocode locations to addresses offline.
ReverseGeocodeUse an online service to find the address for a tapped point.