Geocoding

Download Samples Repository

Description

Demonstrates performing a geocode by submitting values for multiple address fields to a local locator.

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

Sample Code

<UserControl x:Class="ArcGISRuntime.Samples.Desktop.OfflineGeocoding"
             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 Background="White">
        <esri:MapView x:Name="MyMapView" WrapAround="True" Grid.Row="0">
			<esri:Map InitialViewpoint="-13044000, 3855000, -13040000, 3858000, 102100">
                <!-- Replace with local basemap for offline use (ArcGISLocalTiledLayer) -->
				<esri:ArcGISTiledMapServiceLayer 
                    ServiceUri="http://services.arcgisonline.com/ArcGIS/rest/services/World_Street_Map/MapServer" />
			</esri:Map>
			<esri:MapView.GraphicsOverlays>
				<esri:GraphicsOverlay ID="graphicsOverlay" />
			</esri:MapView.GraphicsOverlays>
        </esri:MapView>

		<Border x:Name="panelEdit"
				Background="White" BorderBrush="Black" BorderThickness="1"
				HorizontalAlignment="Right" VerticalAlignment="Top"
				Margin="30" Padding="20" Width="375">
			<Border.Effect>
				<DropShadowEffect/>
			</Border.Effect>
			<StackPanel>
                <Grid>
                    <Grid.RowDefinitions>
                        <RowDefinition />
                        <RowDefinition />
                        <RowDefinition />
                        <RowDefinition />
                        <RowDefinition />
                        <RowDefinition />
                    </Grid.RowDefinitions>
                    <Grid.ColumnDefinitions>
                        <ColumnDefinition Width="Auto" />
                        <ColumnDefinition Width="*"/>
                    </Grid.ColumnDefinitions>

                    <TextBlock Grid.Row="0" Grid.ColumnSpan="2" Text="Enter Address Information" FontSize="14" FontWeight="Bold" 
                               HorizontalAlignment="Center" Margin="0,0,0,6" />
                    
                    <TextBlock Grid.Row="1" Grid.Column="0" Text="Address: " 
                               HorizontalAlignment="Right" VerticalAlignment="Center" Margin="3" />
                    <TextBox x:Name="InputAddress" Grid.Row="1" Grid.Column="1" Text="2920 Zoo Dr" Margin="3" />

                    <TextBlock Grid.Row="2" Grid.Column="0" Text="City: " 
                               HorizontalAlignment="Right" VerticalAlignment="Center" Margin="3" />
                    <TextBox x:Name="City" Grid.Row="2" Grid.Column="1" Text="San Diego" Margin="3" />
                    
                    <TextBlock Grid.Row="3" Grid.Column="0" Text="State: "
                               HorizontalAlignment="Right" VerticalAlignment="Center" Margin="3" />
                    <TextBox x:Name="State" Grid.Row="3" Grid.Column="1" Text="CA" Margin="3"/>
                    
                    <TextBlock Grid.Row="4" Grid.Column="0" Text="Zip: "
                               HorizontalAlignment="Right" VerticalAlignment="Center" Margin="3" />
                    <TextBox x:Name="Zip" Grid.Row="4" Grid.Column="1" Text="92101" Margin="3"/>
                </Grid>

                <Button Content="Find Address" Margin="12,12,12,0" Padding="16,5" IsDefault="True" Click="FindButton_Click" />

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

				<ListView x:Name="listResults" DataContext="{Binding ElementName=MyMapView, Path=GraphicsOverlays[graphicsOverlay]}" ItemsSource="{Binding Graphics}" 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="*" />
                                    <ColumnDefinition Width="Auto" />
                                </Grid.ColumnDefinitions>

                                <StackPanel Grid.Column="0">
                                    <StackPanel Margin="4">
                                        <TextBlock Text="{Binding Attributes[Locator].Address}"/>

                                        <TextBlock>
                                            <TextBlock.Text>
                                                <MultiBinding StringFormat="{}{0:0.000}, {1:0.000}">
                                                    <Binding Path="Attributes[Locator].Location.X" />
                                                    <Binding Path="Attributes[Locator].Location.Y" />
                                                </MultiBinding>
                                            </TextBlock.Text>
                                        </TextBlock>
                                    </StackPanel>
                                </StackPanel>
                                
                                <StackPanel Grid.Column="1" VerticalAlignment="Center">
                                    <TextBlock Text="Score" />
                                    <TextBlock Text="{Binding Attributes[Locator].Score, StringFormat=0}" 
                                               FontSize="18" TextAlignment="Center" />
                                </StackPanel>
                            </Grid>
                        </DataTemplate>
                    </ListView.ItemTemplate>
                </ListView>
            </StackPanel>
        </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.Collections.Generic;
using System.Linq;
using System.Threading;
using System.Threading.Tasks;
using System.Windows;
using System.Windows.Controls;

namespace ArcGISRuntime.Samples.Desktop
{
	/// <summary>
	/// Demonstrates performing a geocode by submitting values for multiple address fields to a local locator.
	/// </summary>
	/// <title>Geocoding</title>
	/// <category>Offline</category>
	public partial class OfflineGeocoding : UserControl
	{
		private const string LOCATOR_PATH = @"..\..\..\samples-data\locators\san-diego\san-diego-locator.loc";

		private LocalLocatorTask _locatorTask;
		private GraphicsOverlay _graphicsOverlay;

		/// <summary>Construct Offline Geocoding sample control</summary>
		public OfflineGeocoding()
		{
			InitializeComponent();

			_graphicsOverlay = MyMapView.GraphicsOverlays["graphicsOverlay"];
			SetupRendererSymbols();
		}

		// Setup marker symbol and renderer
		private async void SetupRendererSymbols()
		{
			try
			{
				var markerSymbol = new PictureMarkerSymbol() { Width = 48, Height = 48, YOffset = 24 };
				await markerSymbol.SetSourceAsync(
					new Uri("pack://application:,,,/ArcGISRuntimeSamplesDesktop;component/Assets/RedStickpin.png"));
				_graphicsOverlay.Renderer = new SimpleRenderer() { Symbol = markerSymbol, };
			}
			catch(Exception ex)
			{
				MessageBox.Show("Error occurred : " + ex.Message, "Sample error");
			}
		}

		// Geocode input address and add result graphics to the map
		private async void FindButton_Click(object sender, RoutedEventArgs e)
		{
			try
			{
				progress.Visibility = Visibility.Visible;
				listResults.Visibility = Visibility.Collapsed;
				_graphicsOverlay.GraphicsSource = null;

				// Street, City, State, ZIP
				Dictionary<string, string> address = new Dictionary<string, string>();
				if (!string.IsNullOrEmpty(InputAddress.Text))
					address.Add("Street", InputAddress.Text);
				if (!string.IsNullOrEmpty(City.Text))
					address.Add("City", City.Text);
				if (!string.IsNullOrEmpty(State.Text))
					address.Add("State", State.Text);
				if (!string.IsNullOrEmpty(Zip.Text))
					address.Add("ZIP", Zip.Text);

				if (_locatorTask == null)
					_locatorTask = await Task.Run<LocalLocatorTask>(() => new LocalLocatorTask(LOCATOR_PATH));

				var candidateResults = await _locatorTask.GeocodeAsync(
					address, new List<string> { "Match_addr" }, MyMapView.SpatialReference, CancellationToken.None);

				_graphicsOverlay.GraphicsSource = candidateResults
					.Select(result => new Graphic(result.Location, new Dictionary<string, object> { { "Locator", result } }));

				await MyMapView.SetViewAsync(ExtentFromGraphics().Expand(2));
			}
			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;
				if (_graphicsOverlay.GraphicsSource != null)
					listResults.Visibility = Visibility.Visible;
			}
		}

		// Helper method to retrieve an extent from graphics in the graphics layer
		private Envelope ExtentFromGraphics()
		{
			var graphics = _graphicsOverlay.GraphicsSource;
			if (graphics == null || graphics.Count() == 0)
				return MyMapView.GetCurrentViewpoint(ViewpointType.BoundingGeometry).TargetGeometry.Extent;

			var extent = graphics.First().Geometry.Extent;
			foreach (var graphic in graphics)
			{
				if (graphic == null || graphic.Geometry == null)
					continue;
				extent = extent.Union(graphic.Geometry.Extent);
				MapPoint point = graphic.Geometry as MapPoint;
			}

			return extent;
		}
	}
}
Feedback on this topic?