Skip To Content ArcGIS for Developers Sign In Dashboard

ArcGIS Runtime SDK for .NET

Show location history

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

Display your location history on the map.

Use case

You can track device location history and display it as lines and points on the map. The history can be used to visualize how the user moved through the world, to retrace their steps, or to create new feature geometry. An unmapped trail, for example, could be added to the map using this technique.

How to use the sample

Click, 'Start tracking' to start tracking your location, which will appear as points on the map. A line will connect the points for easier visualization. Click 'Stop tracking' to stop updating the location history.

How it works

  1. If necessary, request location permission from the operating system.
  2. Create a graphics overlay to show each point and another graphics overlay for displaying the route line.
  3. Create a SystemLocationDataSource and start it to begin receiving location updates.
  4. Subscribe to the LocationChanged event to handle location updates.
  5. Every time the location updates, store that location, display a point on the map, and re-create the route line.

Relevant API

  • Location.Position
  • LocationDataSource
  • LocationDataSource.LocationChanged
  • LocationDataSource.UpdateLocation
  • LocationDisplay.AutoPanMode
  • LocationDisplay.DataSource
  • LocationDisplay.IsEnabled
  • MapView.LocationDisplay
  • SystemLocationDataSource

About the data

The sample uses a dark gray basemap with lime and red graphics. A custom location data source that provides fake/random location data is provided to enable easier testing and allow the sample to be useful on desktop/non-mobile devices.

Tags

GPS, bread crumb, breadcrumb, history, movement, navigation, real-time, trace, track, trail

Sample Code

// Copyright 2019 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 Esri.ArcGISRuntime.Geometry;
using Esri.ArcGISRuntime.Location;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Threading.Tasks;
using System.Timers;

namespace ArcGISRuntime.UWP.Samples.ShowLocationHistory
{
    class FakeLocationDataSource : LocationDataSource
    {
        // Center around which the fake locations are centered.
        private readonly MapPoint _circleRouteCenter = new MapPoint(-117.195801, 34.056007, SpatialReferences.Wgs84);

        // List of points around the circle for use in generating fake locations.
        private readonly List<MapPoint> _artificialMapPoints;

        // Update the location about once per second.
        private readonly Timer _timer;

        // Randomizer. Provide a seed if you want predictable behavior.
        private readonly Random _randomizer = new Random();

        // Index keeps track of where on the fake track you are.
        private int _locationIndex = 0;

        public FakeLocationDataSource()
        {
            // Generate the points that will be used.

            // The location will walk around a circle around the point.
            Polygon outerCircle = (Polygon) GeometryEngine.BufferGeodetic(_circleRouteCenter, 1000, LinearUnits.Feet);

            // Get a list of points on the circle from the buffered point.
            _artificialMapPoints = outerCircle.Parts[0].Points.ToList();

            // Create the timer and configure it to repeat every second.
            _timer = new Timer(1000);
            _timer.AutoReset = true;

            // Listen for timer elapsed events.
            _timer.Elapsed += TimerOnElapsed;
        }

        private void TimerOnElapsed(object sender, ElapsedEventArgs e)
        {
            if (_randomizer.Next(0, 10) > 8)
            {
                // Don't send an update about 20% of the time.
                return;
            }

            // Get the next point along the circle.
            MapPoint selectedMapPoint = _artificialMapPoints[_locationIndex % _artificialMapPoints.Count];

            // Calculate a random offset to move the point.
            double horizontalOffset = _randomizer.NextDouble() * .001;
            double verticalOffset = _randomizer.NextDouble() * .001;

            // Create a new random point.
            MapPoint randomMapPoint = new MapPoint(selectedMapPoint.X + horizontalOffset, selectedMapPoint.Y + verticalOffset, selectedMapPoint.SpatialReference);

            // Update the location; this will trigger a `LocationChanged` event.
            this.UpdateLocation(new Location(randomMapPoint, 5, 0, 0, false));

            // Increment the location index.
            _locationIndex++;
        }

        protected override Task OnStartAsync()
        {
            _timer.Start();
            return Task.CompletedTask;
        }

        protected override Task OnStopAsync()
        {
            _timer.Stop();
            return Task.CompletedTask;
        }
    }
}
<UserControl
    x:Class="ArcGISRuntime.UWP.Samples.ShowLocationHistory.ShowLocationHistory"
    xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
    xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
    xmlns:esriUI="using:Esri.ArcGISRuntime.UI.Controls">
    <Grid>
        <esriUI:MapView x:Name="MyMapView" />
        <Border Style="{StaticResource BorderStyle}">
            <Button x:Name="LocationTrackingButton"
                    Content="Start tracking"
                    IsEnabled="False"
                    HorizontalAlignment="Stretch"
                    Click="LocationTrackingButton_OnClick" />
        </Border>
    </Grid>
</UserControl>
// Copyright 2019 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 Esri.ArcGISRuntime.Geometry;
using Esri.ArcGISRuntime.Location;
using Esri.ArcGISRuntime.Mapping;
using Esri.ArcGISRuntime.Symbology;
using Esri.ArcGISRuntime.UI;
using System;
using Windows.UI.Popups;
using Windows.UI.Xaml;

namespace ArcGISRuntime.UWP.Samples.ShowLocationHistory
{
    [ArcGISRuntime.Samples.Shared.Attributes.Sample(
        "Show location history",
        "Location",
        "Display your location history on the map.",
        "")]
    [ArcGISRuntime.Samples.Shared.Attributes.ClassFile("FakeLocationDataSource.cs")]
    public partial class ShowLocationHistory
    {
        // Track whether location tracking is enabled.
        private bool _isTrackingEnabled;

        // Location data source provides location data updates.
        private LocationDataSource _locationDataSource;

        // Graphics overlay to display the location history (points).
        private GraphicsOverlay _locationHistoryOverlay;

        // Graphics overlay to display the line created by the location points.
        private GraphicsOverlay _locationHistoryLineOverlay;

        // Polyline builder to more efficiently manage large location history graphic.
        private PolylineBuilder _polylineBuilder;

        // Track previous location to ensure the route line appears behind the animating location symbol.
        private MapPoint _lastPosition;

        public ShowLocationHistory()
        {
            InitializeComponent();
            Initialize();
        }

        private void Initialize()
        {
            // Create new Map with basemap.
            Map myMap = new Map(Basemap.CreateDarkGrayCanvasVector());

            // Display the map.
            MyMapView.Map = myMap;

            // Create and add graphics overlay for displaying the trail.
            _locationHistoryLineOverlay = new GraphicsOverlay();
            SimpleLineSymbol locationLineSymbol = new SimpleLineSymbol(SimpleLineSymbolStyle.Solid, System.Drawing.Color.Lime, 2);
            _locationHistoryLineOverlay.Renderer = new SimpleRenderer(locationLineSymbol);
            MyMapView.GraphicsOverlays.Add(_locationHistoryLineOverlay);

            // Create and add graphics overlay for showing points.
            _locationHistoryOverlay = new GraphicsOverlay();
            SimpleMarkerSymbol locationPointSymbol = new SimpleMarkerSymbol(SimpleMarkerSymbolStyle.Circle, System.Drawing.Color.Red, 3);
            _locationHistoryOverlay.Renderer = new SimpleRenderer(locationPointSymbol);
            MyMapView.GraphicsOverlays.Add(_locationHistoryOverlay);

            // Create the polyline builder.
            _polylineBuilder = new PolylineBuilder(SpatialReferences.Wgs84);

            // Start location services.
            HandleLocationReady();
        }

        private async void HandleLocationReady()
        {
            // Create the location data source.
            _locationDataSource = new FakeLocationDataSource();
            // Use this instead if you want real location: _locationDataSource = new SystemLocationDataSource();

            try
            {
                // Start the data source.
                await _locationDataSource.StartAsync();

                if (_locationDataSource.IsStarted)
                {
                    // Set the location display data source and enable location display.
                    MyMapView.LocationDisplay.DataSource = _locationDataSource;
                    MyMapView.LocationDisplay.IsEnabled = true;
                    MyMapView.LocationDisplay.AutoPanMode = LocationDisplayAutoPanMode.Recenter;
                    MyMapView.LocationDisplay.InitialZoomScale = 10000;

                    // Enable the button to start location tracking.
                    LocationTrackingButton.IsEnabled = true;
                }
                else
                {
                    ShowMessage("There was a problem enabling location", "Error");
                }
            }
            catch (Exception e)
            {
                System.Diagnostics.Debug.WriteLine(e);
                ShowMessage("There was a problem enabling location", "Error");
            }
        }

        private void ToggleLocationTracking()
        {
            // Toggle location tracking.
            _isTrackingEnabled = !_isTrackingEnabled;

            // Apply new configuration.
            if (_isTrackingEnabled)
            {
                // Configure new symbology first.
                _locationDataSource.LocationChanged += LocationDataSourceOnLocationChanged;

                // Update the UI.
                LocationTrackingButton.Content = "Stop tracking";
            }
            else
            {
                // Stop updating.
                _locationDataSource.LocationChanged -= LocationDataSourceOnLocationChanged;

                // Update the UI.
                LocationTrackingButton.Content = "Start tracking";
            }
        }

        private void LocationDataSourceOnLocationChanged(object sender, Location e)
        {
            // Remove the old line.
            _locationHistoryLineOverlay.Graphics.Clear();

            // Add any previous position to the history.
            if (_lastPosition != null)
            {
                _polylineBuilder.AddPoint(_lastPosition);
                _locationHistoryOverlay.Graphics.Add(new Graphic(_lastPosition));
            }

            // Store the current position.
            _lastPosition = e.Position;

            // Add the updated line.
            _locationHistoryLineOverlay.Graphics.Add(new Graphic(_polylineBuilder.ToGeometry()));
        }

        private void LocationTrackingButton_OnClick(object sender, RoutedEventArgs e) => ToggleLocationTracking();

        private async void ShowMessage(string title, string detail)
        {
            await new MessageDialog(detail, title).ShowAsync();
        }
    }
}