Find a Place

Download Samples Repository

Description

Demonstrates how to use the FindAsync method of an OnlineLocatorTask object to find places by name.

"Desktop" "Store" "Phone" Available for Desktop, Store, Phone

Sample Code

<UserControl x:Class="ArcGISRuntime.Samples.Desktop.FindPlace"
             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 x:Name="LayoutRoot">
        <esri:MapView x:Name="MyMapView" WrapAround="True">
			<esri:Map InitialViewpoint="-117.207,32.686,-117.079,32.739,4326">
                <esri:ArcGISTiledMapServiceLayer 
                    ServiceUri="http://services.arcgisonline.com/ArcGIS/rest/services/World_Street_Map/MapServer" />
            </esri:Map>
			<esri:MapView.GraphicsOverlays>
				<esri:GraphicsOverlay ID="AddressOverlay" />
			</esri:MapView.GraphicsOverlays>
        </esri:MapView>

		<Border Background="White" BorderBrush="Black" BorderThickness="1"
				 HorizontalAlignment="Right" VerticalAlignment="Top"
				 Margin="30" Padding="20">
			<Border.Effect>
			  <DropShadowEffect />
			</Border.Effect>
            <Grid>
                <Grid.RowDefinitions>
                    <RowDefinition Height="Auto" />
                    <RowDefinition Height="Auto" />
                    <RowDefinition Height="*" />
                </Grid.RowDefinitions>
                
                <StackPanel Grid.Row="0">
                    <TextBox x:Name="SearchTextBox" Width="300" Margin="0,0,0,5" Text="coffee shops" FontSize="14" />
                    <Button Content="Find" IsDefault="True" Click="FindButton_Click" Padding="4"/>
                </StackPanel>

                <ProgressBar x:Name="progress" Grid.Row="1" IsIndeterminate="True" Visibility="Collapsed" Margin="12" />

                <ListView x:Name="listResults" Grid.Row="2" Margin="0,12,0,0" Visibility="Collapsed">
                    <ListView.ItemContainerStyle>
                        <Style TargetType="ListViewItem">
                            <Setter Property="HorizontalContentAlignment" Value="Stretch"></Setter>
                            <Setter Property="IsSelected" Value="{Binding Path=IsSelected, Mode=TwoWay}" />
                        </Style>
                    </ListView.ItemContainerStyle>

                    <ListView.ItemTemplate>
                        <DataTemplate>
                            <Grid>
                                <Grid.ColumnDefinitions>
                                    <ColumnDefinition Width="250" />
                                    <ColumnDefinition Width="Auto" />
                                </Grid.ColumnDefinitions>

                                <StackPanel Grid.Column="0">
                                    <StackPanel Margin="4">
                                        <TextBlock Text="{Binding Attributes[Name]}" FontWeight="Bold" TextWrapping="Wrap" />
                                        <TextBlock Text="{Binding Attributes[Address]}" TextWrapping="Wrap" />
                                        <TextBlock>
                                            <Run Text="Location: " />
                                            <Run Text="{Binding Attributes[LocationDisplay]}" />
                                        </TextBlock>
                                    </StackPanel>
                                </StackPanel>
                            </Grid>
                        </DataTemplate>
                    </ListView.ItemTemplate>
                </ListView>
            </Grid>
        </Border>
    </Grid>
</UserControl>
using Esri.ArcGISRuntime.Controls;
using Esri.ArcGISRuntime.Geometry;
using Esri.ArcGISRuntime.Layers;
using Esri.ArcGISRuntime.Symbology;
using Esri.ArcGISRuntime.Tasks.Geocoding;
using System;
using System.Linq;
using System.Threading;
using System.Windows;
using System.Windows.Controls;

namespace ArcGISRuntime.Samples.Desktop
{
	/// <summary>
	/// Demonstrates how to use the FindAsync method of an OnlineLocatorTask object to find places by name.
	/// </summary>
	/// <title>Find a Place</title>
	/// <category>Tasks</category>
	/// <subcategory>Geocoding</subcategory>
	public partial class FindPlace : UserControl
	{
		private const string OnlineLocatorUrl = "http://geocode.arcgis.com/arcgis/rest/services/World/GeocodeServer";

		private GraphicsOverlay _addressOverlay;
		private OnlineLocatorTask _locatorTask;

		/// <summary>Construct find place sample control</summary>
		public FindPlace()
		{
			InitializeComponent();

			_addressOverlay = MyMapView.GraphicsOverlays["AddressOverlay"];

			_locatorTask = new OnlineLocatorTask(new Uri(OnlineLocatorUrl));
			_locatorTask.AutoNormalize = true;

			listResults.ItemsSource = _addressOverlay.Graphics;

			SetSimpleRendererSymbols();
		}

		// Setup the pin graphic and graphics overlay renderer
		private async void SetSimpleRendererSymbols()
		{
			try
			{
				var markerSymbol = new PictureMarkerSymbol() { Width = 48, Height = 48, YOffset = 24 };
				await markerSymbol.SetSourceAsync(new Uri("pack://application:,,,/ArcGISRuntimeSamplesDesktop;component/Assets/RedStickpin.png"));
				var renderer = new SimpleRenderer() { Symbol = markerSymbol };

				_addressOverlay.Renderer = renderer;
			}
			catch (Exception ex)
			{
				MessageBox.Show("Error occurred : " + ex.Message, "Find Place Sample");
			}
		}

		// Find matching places, create graphics and add them to the UI
		private async void FindButton_Click(object sender, RoutedEventArgs e)
		{
			try
			{
				progress.Visibility = Visibility.Visible;
				listResults.Visibility = Visibility.Collapsed;
				_addressOverlay.Graphics.Clear();

                // Get current viewpoints extent from the MapView
                var currentViewpoint = MyMapView.GetCurrentViewpoint(ViewpointType.BoundingGeometry);
                var viewpointExtent = currentViewpoint.TargetGeometry.Extent;

				var param = new OnlineLocatorFindParameters(SearchTextBox.Text)
				{
					SearchExtent = viewpointExtent,
					Location = viewpointExtent.GetCenter(),
					MaxLocations = 5,
					OutSpatialReference = MyMapView.SpatialReference,
					OutFields = new string[] { "Place_addr" }
				};

				var candidateResults = await _locatorTask.FindAsync(param, CancellationToken.None);

				if (candidateResults == null || candidateResults.Count == 0)
					throw new Exception("No candidates found in the current map extent.");

				foreach (var candidate in candidateResults)
					AddGraphicFromLocatorCandidate(candidate);

				var extent = GeometryEngine.Union(_addressOverlay.Graphics.Select(g => g.Geometry)).Extent.Expand(1.1);
				await MyMapView.SetViewAsync(extent);

				listResults.Visibility = Visibility.Visible;
			}
			catch (AggregateException ex)
			{
				var innermostExceptions = ex.Flatten().InnerExceptions;
				if (innermostExceptions != null && innermostExceptions.Count > 0)
					MessageBox.Show(string.Join(" > ", innermostExceptions.Select(i => i.Message).ToArray()));
				else
					MessageBox.Show(ex.Message);
			}
			catch (System.Exception ex)
			{
				MessageBox.Show(ex.Message);
			}
			finally
			{
				progress.Visibility = Visibility.Collapsed;
			}
		}

		private void AddGraphicFromLocatorCandidate(LocatorFindResult candidate)
		{
			var location = GeometryEngine.Project(
				candidate.Feature.Geometry, SpatialReferences.Wgs84) as MapPoint;

			var graphic = new Graphic(location);
			graphic.Attributes["Name"] = candidate.Name;
			graphic.Attributes["Address"] = candidate.Feature.Attributes["Place_addr"];
			graphic.Attributes["LocationDisplay"] = string.Format("{0:0.000}, {1:0.000}", location.X, location.Y);

			_addressOverlay.Graphics.Add(graphic);
		}
	}
}
Feedback on this topic?