ArcGIS API for Silverlight - Library Reference
FindAsync Method
See Also  Example Send comments on this topic
ESRI.ArcGIS.Client.Tasks Namespace > Locator Class : FindAsync Method

parameters
Includes text and additional options for refining or restricting search results.
userToken
A user-defined object that is passed to the method invoked when the asynchronous operation completes.
An asynchronous geoprocessing task to obtain geocoding search results for locations based upon a single input field.

Syntax

Visual Basic (Declaration) 
Public Sub FindAsync( _
   ByVal parameters As LocatorFindParameters, _
   Optional ByVal userToken As Object _
) 
C# 
public void FindAsync( 
   LocatorFindParameters parameters,
   object userToken
)

Remarks

Developers can use the World Geocoding Service by Esri to find point locations of addresses, business names, points of interest, etc. using a single geocoding service. More information about the World Geocoding Service can be found at http://geocode.arcgis.com.

To obtain a list of geocoded locations based upon a single string field and an optional MapPoint input location use the Locator.FindAsync Method. This Method is useful for finding single string items such as place names, store locations, and points-of-interest. The results of this geocode operation are returned via the Locator.FindCompleted Event. The result parameter of the event yields a LocatorFindResult object. This object can be interrogated for its Locations Property which is a list of Location objects. Each Location object has numerous Properties such as .Extent, .Graphic, and .Name that can be used to display the geocoding results in a Map out in tabular format.

Parameters

parameters
Includes text and additional options for refining or restricting search results.
userToken
A user-defined object that is passed to the method invoked when the asynchronous operation completes.

Example

How to use:

When the application opens, click the 'Mark Location' button and then click on the Map (perhaps near Detroit, MI). Then click the 'Find Places' button. A request to Esri's World Geocoding Service will be invoked via the ESRI.ArcGIS.Client.Tasks.Locator.FindAsync Method. Results will be returned for 'Sears' locations within the current Map.Extent. The results of the geocoding search displayed in the FeatureDataGrid are returned in order based upon an internal ArcGIS Server alogorithm that determines the 'best match' based upon Rank, Score, and Distance. Experiment with adjusting what to 'Search For' (ex: Papa Johns, McDoanlds, etc) , the distance 'Within' for preference order (distance is in meters), the 'Max Locations' of hits to return (maximum number of results returned), and whether to restrict return results to those within the 'Search with Current Extent'. You can click on a returned item in the Map and it will become selected (Red) and also highlight that matching record in the FeatureDataGrid.

The XAML code in this example is used in conjunction with the code-behind (C# or VB.NET) to demonstrate the functionality.

NOTE: You will need to add the following XML namespace line at the top of your XAML code:
xmlns:basics="clr-namespace:System.Windows.Controls;assembly=System.Windows.Controls"

The following screen shot corresponds to the code example in this page.

Example of using the Locator.FindAsync Method to find matching place/entities.

XAMLCopy Code
<Grid x:Name="LayoutRoot" Background="White">
  
  <!-- Set up some visual sections of the application. -->
  <Grid.RowDefinitions>
    <RowDefinition Height="*" />
    <RowDefinition Height="5" />
    <RowDefinition Height="150" />
  </Grid.RowDefinitions>
  
  <!-- Define some custom resources that will be used to visualize MapPoint Graphics on the Map. -->
  <Grid.Resources>
  
    <!-- 
    Define a MarkerSymbol in the Resources section of the XAML file. The MarkerSymbol uses a ControlTemplate
    to define two VisualStateGroups which automatically switch symbology on the GraphicsLayer depending 
    on whether individual Graphic objects are selected or not. 
    -->
    <esri:MarkerSymbol x:Key="ResultsMarkerSymbol" >
      <esri:MarkerSymbol.ControlTemplate>
        <ControlTemplate>
          
          <!-- 
          Provide the default look of the MarkerSymbol for the MapPoint Graphic (a solid blue fill). 
          -->
          <Ellipse x:Name="Element" Width="15" Height="15" Fill="Blue">
          
            <!-- 
            Learn more about the VisualStateManager in the MSDN document:
            http://msdn.microsoft.com/en-us/library/system.windows.controls.controltemplate(v=VS.95).aspx 
            Note: The VisualStateManager Class was newly added in the .NET Framework v4.0. If you are running the .NET 
            Framework v3.5 then you can download and Reference the WPFToolkit on Codeplex (http://wpf.codeplex.com) to 
            take advantage of the VisualStateManager Class.
            -->
            <VisualStateManager.VisualStateGroups>
              <VisualStateGroup x:Name="SelectionStates">
              
                <!--
                Specify the Unselected state. Unselecting the graphic will set the values to those of the original symbology 
                value. The use of a Duration and Storyboard provides a smooth transition back. Note that it take 0 seconds
                for the Graphic to be selected and .5 seconds to go back to the Unselected state.
                -->
                <VisualState x:Name="Unselected" >
                  <Storyboard>
                  
                    <!-- 
                    Note how the To="Blue" Attribute matches the default Fill Attribute value of the Path x:Name="Element" for 
                    defining the MapPoint's Symbology.
                    -->
                    <ColorAnimation Storyboard.TargetName="Element" To="Blue" Duration="00:00:00.50"
                     Storyboard.TargetProperty="(Ellipse.Fill).(SolidColorBrush.Color)">
                    </ColorAnimation>
                  </Storyboard>
                </VisualState>
                
                <!--
                Specifying a Selected state. Selecting the graphic will set the values back to Red for the MapPoint. The use of 
                a Duration and Storyboard provides an immediate transition to the state of being selected. Note that it take 
                0 seconds for the Graphic to be selected and .5 seconds to go back to the Unselected state.
                -->
                <VisualState x:Name="Selected">
                  <Storyboard>
                    
                    <!-- 
                    The To="Red" Attribute will become the Fill Attribute value for the Selected state of the Path x:Name="Element" 
                    for defining the MapPoint's Symbology.
                    -->
                    <ColorAnimation Storyboard.TargetName="Element" To="Red" Duration="00:00:00.00"
                     Storyboard.TargetProperty="(Ellipse.Fill).(SolidColorBrush.Color)">
                    </ColorAnimation>
                  </Storyboard>
                </VisualState>
                
              </VisualStateGroup>
            </VisualStateManager.VisualStateGroups>
          </Ellipse>
        </ControlTemplate>
      </esri:MarkerSymbol.ControlTemplate>
    </esri:MarkerSymbol>
    
    <!-- 
    Define the Renderer that will handle the display of MapPoints that are returned from the Locator Task. The MarkerSymbol 
    is based upon VisualStateManager that switches between selections. Selections can be made either by clicking on the
    MapPoint in the Map or by clicking on a record in the FeatureDataGrid.
    -->
    <esri:SimpleRenderer x:Key="ResultsRenderer" Symbol="{StaticResource ResultsMarkerSymbol }"/>
    
    <!--
    Define a MarkerSymbol that will represent where the user clicks on the Map to begin a search for matching items.
    A big solid fill Green diamond will represent where the user clicks on the Map.
    -->
    <esri:SimpleMarkerSymbol x:Key="UserInputLocationMarkerSymbol" Color="Green" Style="Diamond" Size="25"   />
    
    <!-- 
    Define the Renderer that will handle the display of where the user clicks on the Map to begin a search for matching items.
    -->
    <esri:SimpleRenderer x:Key="UserInputLocationRenderer" Symbol="{StaticResource UserInputLocationMarkerSymbol }"/>
    
  </Grid.Resources>
  
  <!-- Add a Map Control. Set the extent to the area around Detroit, MI. -->
  <esri:Map x:Name="MyMap" WrapAround="True" Extent="-9376406,5119598,-8751399,5328206">
    
    <!-- Add a backdrop ArcGISTiledMapServiceLayer. -->
    <esri:ArcGISTiledMapServiceLayer ID="StreetMapLayer" 
     Url="http://services.arcgisonline.com/ArcGIS/rest/services/World_Street_Map/MapServer" />
    
    <!-- 
    Add a GraphicsLayer to hold the input user clicked MapPoint that will serve as input to the Locator Task. 
    The Rendering uses the big green diamond from the user input.
    -->
    <esri:GraphicsLayer ID="UserInputLocationGraphicsLayer" Renderer="{StaticResource UserInputLocationRenderer}"/>
    
    <!-- 
    Add a GraphicsLayer to hold MapPoint Graphics of places that are returned from the Locator Task. The MouseLeftButtonDown 
    Event handler is wired-up or code-behind. The Rendering is a Blue MapPoint for an Unselected Graphic and a Red MapPoint 
    for a Selected Graphic.
    -->
    <esri:GraphicsLayer ID="ResultsGraphicsLayer" Renderer="{StaticResource ResultsRenderer}" 
     MouseLeftButtonDown="GraphicsLayer_MouseLeftButtonDown"/>
    
  </esri:Map>
  
  <!-- Add more visual astehetics to the application. -->
  <Grid HorizontalAlignment="Right" VerticalAlignment="Top" Margin="0,15,15,0" >
    <Rectangle Stroke="Gray" RadiusX="10" RadiusY="10" Fill="#77919191" Margin="0,0,0,5" >
      <Rectangle.Effect>
        <DropShadowEffect/>
      </Rectangle.Effect>
    </Rectangle>
  </Grid>
  <Border Background="#DD919191" BorderThickness="1" CornerRadius="5" HorizontalAlignment="Right"  
   VerticalAlignment="Top" Padding="10" BorderBrush="Black" Margin="0,15,15,0" >
    <Border.Effect>
      <DropShadowEffect/>
    </Border.Effect>
    <Grid HorizontalAlignment="Left">
      <Grid.RowDefinitions>
        <RowDefinition/>
        <RowDefinition/>
        <RowDefinition/>
        <RowDefinition/>
        <RowDefinition/>
      </Grid.RowDefinitions>
      <Grid.ColumnDefinitions>
        <ColumnDefinition/>
        <ColumnDefinition/>
      </Grid.ColumnDefinitions>
      
      <TextBlock x:Name="ResponseTextBlock" Width="300" TextAlignment="Left" TextWrapping="Wrap" Margin="0,0,5,5" 
       Grid.Row="0" Foreground="White" Grid.ColumnSpan="2" Text="Enter search string below to find the matching places"/>
      <TextBlock Text="Search For:" VerticalAlignment="Center" Margin="0,5,0,0" Foreground="White" Grid.Row="1" Grid.Column="0"/>
      
      <!-- Add the default search criteria (i.e. "Sears") for the Locator. The user can change at will. -->
      <TextBox x:Name="TextBox_Query" Width="150" Margin="2,5,5,0" HorizontalAlignment="Left" MaxLength="60" 
       Grid.Row="1" Grid.Column="1" Text="Sears"/>
      
      <TextBlock Text="Within" VerticalAlignment="Center" Margin="0,5,0,0" Foreground="White" Grid.Row="2" Grid.Column="0"/>
      
      <!-- Add default search distance influence weight for finding various search items. The user can change at will. -->
      <TextBox x:Name="TextBox_Distance" Width="150" Margin="2,5,5,0" HorizontalAlignment="Left" MaxLength="60" 
       Grid.Row="2" Grid.Column="1" Text="10000"/>
      
      <TextBlock Text="Max Locations :" Grid.Row="3" Grid.Column="0"  Margin="2,5,5,0" Foreground="White" VerticalAlignment="Center"/>
      
      <!-- Add maximum number of returned search MapPoint items that can be returned. The user can change at will. -->
      <TextBox x:Name="TextBox_MaxLocations" Width="30" Margin="52,5,5,0" Grid.Row="3" Grid.Column="0" Text="50"/>
          
      <!-- 
      Enable the user to only search for items that are contained in the current Map.Extent. If checked on only items in the 
      Map.Extent will be returned. If unchecked, all items in the Locator database are searched and possibly returned. The 
      default is checked on.
      -->
      <CheckBox x:Name="CheckBox_SearchWithinExtent" IsChecked="True" Content="Search with Current Extent" Grid.Row="4" Grid.Column="0" 
       Foreground="White" HorizontalContentAlignment="Center" VerticalAlignment="Center"/>
      
      <!--
      When the user clicks this button there are able to place a big green diamond on the Map. This will serve as the location to
      begin the Locator search task. 
      -->
      <Button x:Name="Button_UserInputLocation" Click="Button_UserInputLocation_Click" Content="Mark Location" Margin="2,5,5,0" Grid.Row="3" 
       Grid.Column="1" />
      
      <!--
      When the user clicks the button the Locator.FindAsync Task is executed. The goal is to find all items that meet the search 
      query and the user input MapPoint location subject to any Map.Extent constraints and return the MapPoint items ranked 
      according to the distance influence factor.
      -->
      <Button x:Name="Button_FindResults" Content="Find Places" Margin="2,5,0,5" Click="Button_FindResults_Click" Grid.Row="4" 
       Grid.Column="1" HorizontalAlignment="Center" Height="25" />
      
    </Grid>
  </Border>
  
  <!-- Splitter to be able to see attribute records as well as the Map. -->
  <basics:GridSplitter Grid.Row="1" HorizontalAlignment="Stretch" />
  
  <!-- Add a FeatureDataGrid to be able to see the attribute values of the returned results that correspond to the MapPoints. -->
  <esri:FeatureDataGrid Grid.Row="2" x:Name="MyDataGrid" Map="{Binding ElementName=MyMap}"
   GraphicsLayer="{Binding ElementName=MyMap, Path=Layers.[ResultsGraphicsLayer]}"/>
  
</Grid>
C#Copy Code
// Member (i.e. Global) variable for the Locator. 
private ESRI.ArcGIS.Client.Tasks.Locator _LocatorTask;
            
// Member (i.e. Global) variable for the GraphicsLayer that the user places a point on the Map for a Locator search. 
private ESRI.ArcGIS.Client.GraphicsLayer _ResultsGraphicsLayer;
            
// Member (i.e. Global) variable for the GraphicsLayer that contains the MapPoint results from the Locator search. 
private ESRI.ArcGIS.Client.GraphicsLayer _UserInputLocationGraphicsLayer;
            
// Member (i.e. Global) variable for the to enable the user to draw a MapPoint on the Map. 
private ESRI.ArcGIS.Client.Draw _Draw;
            
public MainPage()
{
  InitializeComponent();
  
  // Create a new instance of the Locator task using Esri's World Geocoding Service.
  _LocatorTask = new ESRI.ArcGIS.Client.Tasks.Locator("http://geocode.arcgis.com/arcgis/rest/services/World/GeocodeServer");
  
  // Wire-up the Event Handler for when the Locator Task completes. 
  _LocatorTask.FindCompleted += _locatorTask_FindCompleted;
  
  // Wire-up the Event Handler in case we have a problem with the Locator. 
  _LocatorTask.Failed += LocatorTask_Failed;
  
  // Cast the 2nd Layer in the Map to the GraphicsLayer that contains where the user clicked on the Map.
  _UserInputLocationGraphicsLayer = MyMap.Layers[1] as ESRI.ArcGIS.Client.GraphicsLayer;
  
  // Cast the 3rd Layer in the Map to GraphicsLayer that will hold the returned MapPoint Graphics to the user. 
  _ResultsGraphicsLayer = MyMap.Layers[2] as ESRI.ArcGIS.Client.GraphicsLayer;
  
  // Don't enable the user to do a Locator Task search until they have first added a MapPoint to the Map.
  Button_FindResults.IsEnabled = false;
}
            
private void Button_FindResults_Click(object sender, System.Windows.RoutedEventArgs e)
{
  // This button executes the Locator Task to find places the user desires via it's name and a MapPoint placement on the Map.
  
  // If the user clicks the button before the first Locator results have returned, cancel the Locator request.
  if (_LocatorTask.IsBusy)
  {
    _LocatorTask.CancelAsync();
  }
  
  // Define a new LocationFindParamters object. It provides all of the necessary arguments to execute the Locator Task.
  ESRI.ArcGIS.Client.Tasks.LocatorFindParameters myLocatorFindParameters = new ESRI.ArcGIS.Client.Tasks.LocatorFindParameters();
  
  // Only perform work on valid search place items.
  if (string.IsNullOrEmpty(TextBox_Query.Text))
  {
    return;
  }
  
  // Add the search location to the LocationFindParamters object.
  myLocatorFindParameters.Text = TextBox_Query.Text;
  
  // Set the Map.SpatialReference for the LocationFindParamters object.
  myLocatorFindParameters.OutSpatialReference = MyMap.SpatialReference;
  
  // Set the first MapPoint the user clicked in the Map as the spatial search Location of the LocationFindParamters 
  // object. The Locator search tries to find return candidates closest to the search Location and then radiate 
  // outwards based up the LocationFindParamters.Distance Property. 
  if (_UserInputLocationGraphicsLayer.Graphics.Count > 0)
  {
    ESRI.ArcGIS.Client.GraphicCollection myGraphicCollection = _UserInputLocationGraphicsLayer.Graphics;
    ESRI.ArcGIS.Client.Graphic myGraphic = myGraphicCollection[0];
    myLocatorFindParameters.Location = myGraphic.Geometry as ESRI.ArcGIS.Client.Geometry.MapPoint;
  }
  
  // Specifying a LocationFindParamters.Distance enables the Locator to rank search hits found that are returned to the 
  // user. The returned result MapPoints are in order with those closest to the LocatorFindParameters.Location MapPoint
  // being first in the Result Locations collection and those farther away from the LocatorFindParameters.Location MapPoint 
  // being later in the Result Locations collection. Details about the how the Distance parameter work can be found in the 
  // documentation of Esri's World Geocoding Service.
  if (!(string.IsNullOrEmpty(TextBox_Distance.Text)))
  {
    myLocatorFindParameters.Distance = Convert.ToDouble(TextBox_Distance.Text);
  }
  
  // Enable the user to set a maximum number of returned search hits returned from the Locator Task.
  if (!(string.IsNullOrEmpty(TextBox_MaxLocations.Text)))
  {
    myLocatorFindParameters.MaxLocations = Convert.ToInt32(TextBox_MaxLocations.Text);
  }
  
  // If the LocatorFindParameters.SearchExtent is set then ONLY search hits that are within that extent are returned from the
  // Locator Task servcice. In this case the current Map.Extent can be used. For a mobile type of application you could define
  // the SearchExtent based upon some calculated relevant value (for example: only find pizza shops with 5 miles of the cell phone). 
  if (CheckBox_SearchWithinExtent.IsChecked == true)
  {
    myLocatorFindParameters.SearchExtent = MyMap.Extent;
  }
  
  // Execute the Locator Task using the user defined parameters they set in the GUI. 
  _LocatorTask.FindAsync(myLocatorFindParameters, TextBox_Query.Text);
}
            
private void _locatorTask_FindCompleted(object sender, ESRI.ArcGIS.Client.Tasks.LocatorFindEventArgs e)
{
  // This function executes when the Locator Task has completed.
  
  // Make sure we have some valid results before displaying them to the user. 
  if (e.Result != null && e.Result.Locations.Count > 0)
  {
    // Clear out any prior runs of the Locator Task.
    _ResultsGraphicsLayer.Graphics.Clear();
    
    // Loop through the collection of Location objects (i.e. results found from the Locator Task.
    foreach (ESRI.ArcGIS.Client.Tasks.Location oneLocation in e.Result.Locations)
    {
      // Add some of the returned Location attributes to the Results GraphicsLayer. 
      oneLocation.Graphic.Attributes["Name"] = oneLocation.Name;
      oneLocation.Graphic.Attributes["location"] = oneLocation.Graphic.Geometry;
      // We want to display the Score as an integer value (i.e. truncate the double that is returned)
      oneLocation.Graphic.Attributes["Score"] = Convert.ToInt32(oneLocation.Graphic.Attributes["Score"]);
      _ResultsGraphicsLayer.Graphics.Add(oneLocation.Graphic);
    }
  }
}
            
private void Button_UserInputLocation_Click(object sender, System.Windows.RoutedEventArgs e)
{
  // This function executes when the user clicks the button to add a search location MapPoint on the Map.
  
  // Clear out any existing MapPoint Graphics.
  _UserInputLocationGraphicsLayer.ClearGraphics();
  
  //  Create a new instance of the Draw object that allows a user to place a MapPoint on the Map for searching items.
  _Draw = new ESRI.ArcGIS.Client.Draw();
  _Draw.Map = MyMap;
  _Draw.DrawMode = ESRI.ArcGIS.Client.DrawMode.Point;
  _Draw.IsEnabled = true;
  
  // Wire-up the Event Handler to allow the user to draw MapPoint Graphics on the Map. 
  _Draw.DrawComplete += myDraw_DrawComplete;
}
            
private void myDraw_DrawComplete(object sender, ESRI.ArcGIS.Client.DrawEventArgs e)
{
  // This function executes because the user has clicked on the Map with the mouse/tap gesture.
  
  // Create a new Graphics and set its Geometry.
  ESRI.ArcGIS.Client.Graphic myGraphic = new ESRI.ArcGIS.Client.Graphic();
  myGraphic.Geometry = e.Geometry;
  
  // Add the user drawn Graphic to the GraphicsLayer.
  _UserInputLocationGraphicsLayer.Graphics.Add(myGraphic);
  
  // Disable the ability to add more Graphics unless the user re-clicks the Button_UserInputLocation.
  _Draw.IsEnabled = false;
  
  // Enable the user to do a Locator Task search now that a MapPoint Graphics has been added to the Map.
  Button_FindResults.IsEnabled = true;
}
            
private void LocatorTask_Failed(object sender, ESRI.ArcGIS.Client.Tasks.TaskFailedEventArgs e)
{
  // We had a problem with the Locator Task. Inform the use with the problem.
  System.Windows.MessageBox.Show("Locator service failed: " + e.Error.ToString());
}
            
private void GraphicsLayer_MouseLeftButtonDown(object sender, ESRI.ArcGIS.Client.GraphicMouseButtonEventArgs e)
{
  // Change the selection of the MapPoint Graphics in the returned results Layer from the Locator task. 
  // Selected is Red. Unselected is Blue.
  e.Graphic.Selected = !e.Graphic.Selected;
}
VB.NETCopy Code
' Member (i.e. Global) variable for the Locator. 
Private _LocatorTask As ESRI.ArcGIS.Client.Tasks.Locator
            
' Member (i.e. Global) variable for the GraphicsLayer that the user places a point on the Map for a Locator search. 
Private _ResultsGraphicsLayer As ESRI.ArcGIS.Client.GraphicsLayer
            
' Member (i.e. Global) variable for the GraphicsLayer that contains the MapPoint results from the Locator search. 
Private _UserInputLocationGraphicsLayer As ESRI.ArcGIS.Client.GraphicsLayer
            
' Member (i.e. Global) variable for the to enable the user to draw a MapPoint on the Map. 
Private _Draw As ESRI.ArcGIS.Client.Draw
            
Public Sub New()
  
  InitializeComponent()
  
  ' Create a new instance of the Locator task using Esri's World Geocoding Service.
  _LocatorTask = New ESRI.ArcGIS.Client.Tasks.Locator("http://geocode.arcgis.com/arcgis/rest/services/World/GeocodeServer")
  
  ' Wire-up the Event Handler for when the Locator Task completes. 
  AddHandler _LocatorTask.FindCompleted, AddressOf _locatorTask_FindCompleted
  
  ' Wire-up the Event Handler in case we have a problem with the Locator. 
  AddHandler _LocatorTask.Failed, AddressOf LocatorTask_Failed
  
  ' Cast the 2nd Layer in the Map to the GraphicsLayer that contains where the user clicked on the Map.
  _UserInputLocationGraphicsLayer = TryCast(MyMap.Layers(1), ESRI.ArcGIS.Client.GraphicsLayer)
  
  ' Cast the 3rd Layer in the Map to GraphicsLayer that will hold the returned MapPoint Graphics to the user. 
  _ResultsGraphicsLayer = TryCast(MyMap.Layers(2), ESRI.ArcGIS.Client.GraphicsLayer)
  
  ' Don't enable the user to do a Locator Task search until they have first added a MapPoint to the Map.
  Button_FindResults.IsEnabled = False
  
End Sub
            
Private Sub Button_FindResults_Click(ByVal sender As Object, ByVal e As RoutedEventArgs)
  
  ' This button executes the Locator Task to find places the user desires via it's name and a MapPoint placement on the Map.
  
  ' If the user clicks the button before the first Locator results have returned, cancel the Locator request.
  If _LocatorTask.IsBusy Then
   _LocatorTask.CancelAsync()
  End If
  
  ' Define a new LocationFindParamters object. It provides all of the necessary arguments to execute the Locator Task.
  Dim myLocatorFindParameters As ESRI.ArcGIS.Client.Tasks.LocatorFindParameters = New ESRI.ArcGIS.Client.Tasks.LocatorFindParameters
  
  ' Only perform work on valid search place items.
  If String.IsNullOrEmpty(TextBox_Query.Text) Then
    Return
  End If
  
  ' Add the search location to the LocationFindParamters object.
  myLocatorFindParameters.Text = TextBox_Query.Text
  
  ' Set the Map.SpatialReference for the LocationFindParamters object.
  myLocatorFindParameters.OutSpatialReference = MyMap.SpatialReference
  
  ' Set the first (in case there is more than one) MapPoint the user clicked in the Map as the spatial search Location 
  ' of the LocationFindParamters object. The Locator search tries to find return candidates closest to the search Location
  ' and then radiate outwards based up the LocationFindParamters.Distance Property. 
  If _UserInputLocationGraphicsLayer.Graphics.Count > 0 Then
    myLocatorFindParameters.Location = TryCast(_UserInputLocationGraphicsLayer.Graphics.FirstOrDefault().Geometry, ESRI.ArcGIS.Client.Geometry.MapPoint)
  End If
  
  ' Specifying a LocationFindParamters.Distance enables the Locator to rank search hits found that are returned to the 
  ' user. The returned result MapPoints are in order with those closest to the LocatorFindParameters.Location MapPoint
  ' being first in the Result Locations collection and those farther away from the LocatorFindParameters.Location MapPoint 
  ' being later in the Result Locations collection. Details about the how the Distance parameter work can be found in the 
  ' documentation of Esri's World Geocoding Service.
  If Not (String.IsNullOrEmpty(TextBox_Distance.Text)) Then
    myLocatorFindParameters.Distance = Convert.ToDouble(TextBox_Distance.Text)
  End If
  
  ' Enable the user to set a maximum number of returned search hits returned from the Locator Task.
  If Not (String.IsNullOrEmpty(TextBox_MaxLocations.Text)) Then
    myLocatorFindParameters.MaxLocations = Convert.ToInt32(TextBox_MaxLocations.Text)
  End If
  
  ' If the LocatorFindParameters.SearchExtent is set then ONLY search hits that are within that extent are returned from the
  ' Locator Task servcice. In this case the current Map.Extent can be used. For a mobile type of application you could define
  ' the SearchExtent based upon some calculated relevant value (for example: only find pizza shops with 5 miles of the cell phone). 
  If CheckBox_SearchWithinExtent.IsChecked = True Then
    myLocatorFindParameters.SearchExtent = MyMap.Extent
  End If
  
  ' Execute the Locator Task using the user defined parameters they set in the GUI. 
  _LocatorTask.FindAsync(myLocatorFindParameters, TextBox_Query.Text)
  
End Sub
            
Private Sub _locatorTask_FindCompleted(ByVal sender As Object, ByVal e As ESRI.ArcGIS.Client.Tasks.LocatorFindEventArgs)
  
  ' This function executes when the Locator Task has completed.
  
  ' Make sure we have some valid results before displaying them to the user. 
  If e.Result IsNot Nothing AndAlso e.Result.Locations.Count > 0 Then
    
    ' Clear out any prior runs of the Locator Task.
    _ResultsGraphicsLayer.Graphics.Clear()
    
    ' Loop through the collection of Location objects (i.e. results found from the Locator Task.
    For Each oneLocation As ESRI.ArcGIS.Client.Tasks.Location In e.Result.Locations
      
      ' Add some of the returned Location attributes to the Results GraphicsLayer. 
      oneLocation.Graphic.Attributes("Name") = oneLocation.Name
      oneLocation.Graphic.Attributes("location") = oneLocation.Graphic.Geometry
      ' We want to display the Score as an integer value (i.e. truncate the double that is returned)
      oneLocation.Graphic.Attributes("Score") = Convert.ToInt32(oneLocation.Graphic.Attributes("Score"))
      _ResultsGraphicsLayer.Graphics.Add(oneLocation.Graphic)
      
    Next oneLocation
    
  End If
  
End Sub
            
Private Sub Button_UserInputLocation_Click(ByVal sender As Object, ByVal e As RoutedEventArgs)
  
  ' This function executes when the user clicks the button to add a search location MapPoint on the Map.
  
  ' Clear out any existing MapPoint Graphics.
  _UserInputLocationGraphicsLayer.ClearGraphics()
  
  '  Create a new instance of the Draw object that allows a user to place a MapPoint on the Map for searching items.
  _Draw = New ESRI.ArcGIS.Client.Draw
  _Draw.Map = MyMap
  _Draw.DrawMode = ESRI.ArcGIS.Client.DrawMode.Point
  _Draw.IsEnabled = True
  
  ' Wire-up the Event Handler to allow the user to draw MapPoint Graphics on the Map. 
  AddHandler _Draw.DrawComplete, AddressOf myDraw_DrawComplete
  
End Sub
            
Private Sub myDraw_DrawComplete(sender As Object, e As ESRI.ArcGIS.Client.DrawEventArgs)
  
  ' This function executes because the user has clicked on the Map with the mouse/tap gesture.
  
  ' Create a new Graphics and set its Geometry.
  Dim myGraphic As ESRI.ArcGIS.Client.Graphic = New ESRI.ArcGIS.Client.Graphic
  myGraphic.Geometry = e.Geometry
  
  ' Add the user drawn Graphic to the GraphicsLayer.
  _UserInputLocationGraphicsLayer.Graphics.Add(myGraphic)
  
  ' Disable the ability to add more Graphics unless the user re-clicks the Button_UserInputLocation.
  _Draw.IsEnabled = False
  
  ' Enable the user to do a Locator Task search now that a MapPoint Graphics has been added to the Map.
  Button_FindResults.IsEnabled = True
  
End Sub
            
Private Sub LocatorTask_Failed(ByVal sender As Object, ByVal e As ESRI.ArcGIS.Client.Tasks.TaskFailedEventArgs)
  
  ' We had a problem with the Locator Task. Inform the use with the problem.
  MessageBox.Show("Locator service failed: " + e.Error.ToString)
  
End Sub
            
Private Sub GraphicsLayer_MouseLeftButtonDown(ByVal sender As Object, ByVal e As ESRI.ArcGIS.Client.GraphicMouseButtonEventArgs)
  
  ' Change the selection of the MapPoint Graphics in the returned results Layer from the Locator task. 
  ' Selected is Red. Unselected is Blue.
  e.Graphic.Selected = Not e.Graphic.Selected
  
End Sub

Requirements

Target Platforms: Windows XP Professional, Windows Server 2003 family, Windows Vista, Windows Server 2008 family, Windows 7

See Also

© ESRI, Inc. All Rights Reserved.