Skip To Content ArcGIS for Developers Sign In Dashboard

ArcGIS Runtime SDK for .NET

List transformations by suitability

This code sample is available for these platforms:
View Sample on GitHub

Get a list of suitable transformations for projecting a geometry between two spatial references with different horizontal datums.

screenshot

Use case

Transformations (sometimes known as datum or geographic transformations) are used when projecting data from one spatial reference to another when there is a difference in the underlying datum of the spatial references. Transformations can be mathematically defined by specific equations (equation-based transformations), or may rely on external supporting files (grid-based transformations). Choosing the most appropriate transformation for a situation can ensure the best possible accuracy for this operation. Some users familiar with transformations may wish to control which transformation is used in an operation.

How to use the sample

Select a transformation from the list to see the result of projecting the point from EPSG:27700 to EPSG:3857 using that transformation. The result is shown as a red cross; you can visually compare the original blue point with the projected red cross.

Select 'Consider current extent' to limit the transformations that are appropriate for the current extent.

If the selected transformation is not usable (has missing grid files) then an error is displayed.

How it works

  1. Pass the input and output spatial references to TransformationCatalog.GetTransformationsBySuitability for transformations based on the map's spatial reference OR additionally provide an extent argument to only return transformations suitable to the extent. This returns a list of ranked transformations.
  2. Use one of the DatumTransformation objects returned to project the input geometry to the output spatial reference.

Relevant API

  • DatumTransformation
  • GeographicTransformation
  • GeographicTransformationStep
  • GeometryEngine
  • GeometryEngine.Project
  • TransformationCatalog

About the data

The map starts out zoomed into the grounds of the Royal Observatory, Greenwich. The initial point is in the EPSG:27700 spatial reference, which was created by the United Kingdom Ordnance Survey. The spatial reference after projection is in the EPSG:3857 spatial reference, commonly known as web mercator.

Additional information

Some transformations aren't available until transformation data is provided.

This sample can be used with or without provisioning projection engine data to your device. If you do not provision data, a limited number of transformations will be available.

Tags

datum, geodesy, projection, spatial reference, transformation

Sample Code

<UserControl
    x:Class="ArcGISRuntime.UWP.Samples.ListTransformations.ListTransformations"
    x:Name="_this"
    xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
    xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
    xmlns:local="using:ArcGISRuntime.UWP.Samples.ListTransformations"
    xmlns:esriUI="using:Esri.ArcGISRuntime.UI.Controls">
    <Grid DataContext="{Binding ElementName=_this}">
        <esriUI:MapView x:Name="MyMapView" />
        <Border Style="{StaticResource BorderStyle}">
            <Grid>
                <Grid.RowDefinitions>
                    <RowDefinition Height="Auto" />
                    <RowDefinition Height="Auto" />
                    <RowDefinition Height="Auto" />
                    <RowDefinition Height="Auto" />
                </Grid.RowDefinitions>
                <Grid.ColumnDefinitions>
                    <ColumnDefinition Width="*" />
                    <ColumnDefinition Width="*" />
                </Grid.ColumnDefinitions>
                <TextBlock x:Name="InSpatialRefTextBox"
                           Grid.Row="0" Grid.Column="0"
                           FontWeight="SemiBold" />
                <TextBlock x:Name="OutSpatialRefTextBox"
                           HorizontalAlignment="Right"
                           Grid.Row="0" Grid.Column="1"
                           FontWeight="SemiBold" />
                <CheckBox x:Name="UseExtentCheckBox"
                          Grid.Row="1" Grid.Column="0" Grid.ColumnSpan="2"
                          Margin="0,5,0,0"
                          Content="Consider current extent"
                          IsChecked="False"
                          Checked="UseExtentCheckBox_CheckChanged"
                          Unchecked="UseExtentCheckBox_CheckChanged" />
                <ListView x:Name="TransformationsListBox"
                          Grid.Row="2" Grid.Column="0" Grid.ColumnSpan="2"
                          BorderBrush="Black" BorderThickness="1" Padding="0"
                          Height="200"
                          ItemsSource="{Binding Path=SuitableTransformationsList}"
                          SelectionChanged="TransformationsListBox_Selected">
                    <ListView.ItemTemplate>
                        <DataTemplate x:DataType="local:DatumTransformationListBoxItem">
                            <UserControl>
                                <TextBlock x:Name="TransformNameTextBlock"
                                           Text="{Binding Path=TransformationObject.Name}"
                                           TextWrapping="Wrap">
                                    <!-- View states to manage display of unavailable transforms, and the default transform. -->
                                    <VisualStateManager.VisualStateGroups>
                                        <VisualStateGroup>
                                            <!-- If missing PE files locally, the transform is unavailable. -->
                                            <VisualState x:Name="UnavailableTransformState">
                                                <VisualState.StateTriggers>
                                                    <StateTrigger
                                                        IsActive="{x:Bind TransformationObject.IsMissingProjectionEngineFiles, Mode=OneWay}" />
                                                </VisualState.StateTriggers>
                                                <Storyboard>
                                                    <DoubleAnimation Storyboard.TargetName="TransformNameTextBlock"
                                                                     Storyboard.TargetProperty="(TextBlock.Opacity)"
                                                                     To="0.5" Duration="0:0:1" />
                                                </Storyboard>
                                            </VisualState>
                                            <!-- One transform is the default, highlight it in blue. -->
                                            <VisualState x:Name="DefaultTransformState">
                                                <VisualState.StateTriggers>
                                                    <StateTrigger IsActive="{x:Bind IsDefault, Mode=OneWay}" />
                                                </VisualState.StateTriggers>
                                                <Storyboard>
                                                    <ColorAnimation Duration="0:0:1" To="Blue"
                                                                    Storyboard.TargetProperty="(TextBlock.Foreground).(SolidColorBrush.Color)"
                                                                    Storyboard.TargetName="TransformNameTextBlock" />
                                                </Storyboard>
                                            </VisualState>
                                        </VisualStateGroup>
                                    </VisualStateManager.VisualStateGroups>
                                </TextBlock>
                            </UserControl>
                        </DataTemplate>
                    </ListView.ItemTemplate>
                </ListView>
                <TextBlock x:Name="MessagesTextBox"
                           Grid.Row="3" Grid.Column="0" Grid.ColumnSpan="2"
                           Margin="0,5,0,0"
                           TextWrapping="Wrap" FontWeight="SemiBold" />
            </Grid>
        </Border>
    </Grid>
</UserControl>
// Copyright 2018 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 Esri.ArcGISRuntime;
using Esri.ArcGISRuntime.Geometry;
using Esri.ArcGISRuntime.Mapping;
using Esri.ArcGISRuntime.Symbology;
using Esri.ArcGISRuntime.UI;
using System.Collections.Generic;
using System.ComponentModel;
using System.Drawing;
using Windows.UI.Popups;
using Windows.UI.Xaml;

namespace ArcGISRuntime.UWP.Samples.ListTransformations
{
    [ArcGISRuntime.Samples.Shared.Attributes.Sample(
        "List transformations by suitability",
        "Geometry",
        "This sample demonstrates how to use the TransformationCatalog to get a list of available DatumTransformations that can be used to project a Geometry between two different SpatialReferences, and how to use one of the transformations to perform the GeometryEngine.project operation. The TransformationCatalog is also used to set the location of files upon which grid-based transformations depend, and to find the default transformation used for the two SpatialReferences.",
        "Tap on a listed transformation to re-project the point geometry (shown with a blue square) using the selected transformation. The reprojected geometry will be shown in red. If there are grid-based transformations for which projection engine files are not available locally, these will be shown in gray in the list. The default transformation is shown in bold. To download the additional transformation data, log on to your developers account (http://developers.arcgis.com), click the 'Download APIs' button on the dashboard page, and download the 'Coordinate System Data' archive from the 'Supplemental ArcGIS Runtime Data' tab. Unzip the archive to the 'SampleData' sub-folder of the ApplicationData directory, which can be found for each platform at run time with System.Environment.GetFolderPath(System.Environment.SpecialFolder.ApplicationData).",
        "Featured")]
	[ArcGISRuntime.Samples.Shared.Attributes.OfflineData()]
    public partial class ListTransformations : INotifyPropertyChanged
    {
        // Point whose coordinates will be projected using a selected transform.
        private MapPoint _originalPoint;

        // Graphic representing the projected point.
        private Graphic _projectedPointGraphic;

        // GraphicsOverlay to hold the point graphics.
        private GraphicsOverlay _pointsOverlay;

        // Property to expose the list of datum transformations for binding to the list box.
        private IReadOnlyList<DatumTransformationListBoxItem> _datumTransformations;
        public IReadOnlyList<DatumTransformationListBoxItem> SuitableTransformationsList
        {
            get
            {
                return _datumTransformations;
            }
            set
            {
                _datumTransformations = value;
                OnPropertyChanged("SuitableTransformationsList");
            }
        }

        // Implement INotifyPropertyChanged to indicate when the list of transformations has been updated.
        public event PropertyChangedEventHandler PropertyChanged;
        private void OnPropertyChanged(string propertyName)
        {
            if (PropertyChanged != null)
            {
                PropertyChanged(this, new PropertyChangedEventArgs(propertyName));
            }
        }

        public ListTransformations()
        {
            InitializeComponent();

            Initialize();
        }

        private async void Initialize()
        {
            // Create the map.
            Map myMap = new Map(Basemap.CreateImageryWithLabels());

            // Create a point in the Greenwich observatory courtyard in London, UK, the location of the prime meridian. 
            _originalPoint = new MapPoint(538985.355, 177329.516, SpatialReference.Create(27700));

            // Set the initial extent to an extent centered on the point.
            Viewpoint initialViewpoint = new Viewpoint(_originalPoint, 5000);
            myMap.InitialViewpoint = initialViewpoint;

            // Add the map to the map view.
            MyMapView.Map = myMap;

            // Create a graphics overlay to hold the original and projected points.
            _pointsOverlay = new GraphicsOverlay();
            MyMapView.GraphicsOverlays.Add(_pointsOverlay);

            // Add the point as a graphic with a blue square.
            SimpleMarkerSymbol markerSymbol = new SimpleMarkerSymbol(SimpleMarkerSymbolStyle.Square, Color.Blue, 15);
            Graphic originalGraphic = new Graphic(_originalPoint, markerSymbol);
            _pointsOverlay.Graphics.Add(originalGraphic);

            // Get the path to the projection engine data (if it exists).
            string peFolderPath = GetProjectionDataPath();
            if (!String.IsNullOrEmpty(peFolderPath))
            {
                TransformationCatalog.ProjectionEngineDirectory = peFolderPath;
                MessagesTextBox.Text = "Using projection data found at '" + peFolderPath + "'";
            }
            else
            {
                MessagesTextBox.Text = "Projection engine data not found.";
            }

            try
            {
                // Wait for the map to load so that it has a spatial reference.
                await myMap.LoadAsync();

                // Show the input and output spatial reference.
                InSpatialRefTextBox.Text = "In WKID = " + _originalPoint.SpatialReference.Wkid;
                OutSpatialRefTextBox.Text = "Out WKID = " + myMap.SpatialReference.Wkid;

                // Create a list of transformations to fill the UI list box.
                GetSuitableTransformations(_originalPoint.SpatialReference, myMap.SpatialReference, UseExtentCheckBox.IsChecked == true);
            }
            catch (Exception e)
            {
                await new MessageDialog(e.ToString(), "Error").ShowAsync();
            }
        }

        // Function to get suitable datum transformations for the specified input and output spatial references.
        private void GetSuitableTransformations(SpatialReference inSpatialRef, SpatialReference outSpatialRef, bool considerExtent)
        {
            // Get suitable transformations. Use the current extent to evaluate suitability, if requested.
            IReadOnlyList<DatumTransformation> transformations;
            if (considerExtent)
            {
                Envelope currentExtent = MyMapView.GetCurrentViewpoint(ViewpointType.BoundingGeometry).TargetGeometry as Envelope;
                transformations = TransformationCatalog.GetTransformationsBySuitability(inSpatialRef, outSpatialRef, currentExtent);
            }
            else
            {
                transformations = TransformationCatalog.GetTransformationsBySuitability(inSpatialRef, outSpatialRef);
            }

            // Get the default transformation for the specified input and output spatial reference.
            DatumTransformation defaultTransform = TransformationCatalog.GetTransformation(inSpatialRef, outSpatialRef);

            List<DatumTransformationListBoxItem> transformationItems = new List<DatumTransformationListBoxItem>();
            // Wrap the transformations in a class that includes a boolean to indicate if it's the default transformation.
            foreach (DatumTransformation transform in transformations)
            {
                DatumTransformationListBoxItem item = new DatumTransformationListBoxItem(transform)
                {
                    IsDefault = (transform.Name == defaultTransform.Name)
                };
                transformationItems.Add(item);
            }

            // Set the transformation list property that the list box binds to.
            SuitableTransformationsList = transformationItems;
        }

        private void TransformationsListBox_Selected(object sender, RoutedEventArgs e)
        {
            // Get the selected transform from the list box. Return if there isn't a selected item.
            DatumTransformationListBoxItem selectedListBoxItem = TransformationsListBox.SelectedItem as DatumTransformationListBoxItem;
            if (selectedListBoxItem == null) { return; }

            DatumTransformation selectedTransform = selectedListBoxItem.TransformationObject;
            
            try
            {
                // Project the original point using the selected transform.
                MapPoint projectedPoint = (MapPoint)GeometryEngine.Project(_originalPoint, MyMapView.SpatialReference, selectedTransform);

                // Update the projected graphic (if it already exists), create it otherwise.
                if (_projectedPointGraphic != null)
                {
                    _projectedPointGraphic.Geometry = projectedPoint;
                }
                else
                {
                    // Create a symbol to represent the projected point (a cross to ensure both markers are visible).
                    SimpleMarkerSymbol projectedPointMarker = new SimpleMarkerSymbol(SimpleMarkerSymbolStyle.Cross, Color.Red, 15);

                    // Create the point graphic and add it to the overlay.
                    _projectedPointGraphic = new Graphic(projectedPoint, projectedPointMarker);
                    _pointsOverlay.Graphics.Add(_projectedPointGraphic);
                }

                MessagesTextBox.Text = "Projected point using transform: " + selectedTransform.Name;
            }
            catch (ArcGISRuntimeException ex)
            {
                // Exception if a transformation is missing grid files.
                MessagesTextBox.Text = "Error using selected transformation: " + ex.Message;

                // Remove the projected point graphic (if it exists).
                if (_projectedPointGraphic != null && _pointsOverlay.Graphics.Contains(_projectedPointGraphic))
                {
                    _pointsOverlay.Graphics.Remove(_projectedPointGraphic);
                    _projectedPointGraphic = null;
                }
            }
        }

        private void UseExtentCheckBox_CheckChanged(object sender, RoutedEventArgs e)
        {
            // Recreate the contents of the datum transformations list box.
            GetSuitableTransformations(_originalPoint.SpatialReference, MyMapView.Map.SpatialReference, UseExtentCheckBox.IsChecked == true);
        }

        private string GetProjectionDataPath()
        {
            // Return the projection data path; note that this is not valid by default. 
            //You must manually download the projection engine data and update the path returned here. 
            return "";
        }
    }

    // A class that wraps a DatumTransformation object and adds a property that indicates if it's the default transformation.
    public class DatumTransformationListBoxItem
    {
        // Datum transformation object.
        public DatumTransformation TransformationObject { get; set; }

        // Whether or not this transformation is the default (for the specified in/out spatial reference).
        public bool IsDefault { get; set; }

        // Constructor that takes the DatumTransformation object to wrap.
        public DatumTransformationListBoxItem(DatumTransformation transformation)
        {
            TransformationObject = transformation;
        }
    }
}