Show device location history

View on GitHub

Display your device's location history on the map.

Image of show device location history

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

Tap 'Start Tracking' to start tracking your location, which will appear as points on the map. A line will connect the points for easier visualization. Tap 'Stop Tracking' to stop updating the location history. This sample uses a simulated data source to allow the sample to be useful on desktop/non-mobile devices. To track a user's real position, use the LocationDataSource instead.

How it works

  1. Create a graphics overlay to show each point and another graphics overlay for displaying the route line.
  2. Create a SimulatedLocationDataSource and initialize it with a polyline. Start the SimulatedLocationDataSource to begin receiving location updates.
  • NOTE: To track a user's real position, use LocationDataSource instead.
  1. Subscribe to the onLocationChanged event to handle location updates.
  2. Every time the location updates, store that location, display a point on the map, and recreate the route line.

Relevant API

  • Graphic
  • GraphicsOverlay
  • LocationDataSource
  • LocationDisplay
  • LocationDisplayAutoPanMode
  • PolylineBuilder
  • SimpleLineSymbol
  • SimpleMarkerSymbol
  • SimpleRenderer
  • SimulatedLocationDataSource

About the data

A custom set of points is used to create a Polyline and initialize a SimulatedLocationDataSource. This simulated location data source enables easier testing and allows the sample to be used on devices without an actively updating GPS signal.

Tags

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

Sample Code

show_device_location_history.dart
Use dark colors for code blocksCopy
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
//
// Copyright 2024 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
//
//   https://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.
//

import 'dart:async';

import 'package:arcgis_maps/arcgis_maps.dart';
import 'package:flutter/material.dart';
import 'package:flutter/services.dart';

import '../../utils/sample_state_support.dart';

class ShowDeviceLocationHistory extends StatefulWidget {
  const ShowDeviceLocationHistory({super.key});

  @override
  State<ShowDeviceLocationHistory> createState() =>
      _ShowDeviceLocationHistoryState();
}

class _ShowDeviceLocationHistoryState extends State<ShowDeviceLocationHistory>
    with SampleStateSupport {
  // Create a controller for the map view.
  final _mapViewController = ArcGISMapView.createController();
  // A location data source to simulate location updates.
  final _locationDataSource = SimulatedLocationDataSource();
  // Subscription to listen for location changes.
  StreamSubscription? _locationSubscription;
  // A GraphicsOverlay to display the location history polyline.
  final _locationHistoryLineOverlay = GraphicsOverlay();
  // A GraphicsOverlay to display the location history points.
  final _locationHistoryPointOverlay = GraphicsOverlay();
  // A PolylineBuilder to build the location history polyline.
  final _polylineBuilder =
      PolylineBuilder(spatialReference: SpatialReference.wgs84);
  // A flag for when the map view is ready and controls can be used.
  var _ready = false;
  // A flag for toggling location tracking.
  var _enableTracking = false;

  @override
  void dispose() {
    // When exiting, stop the location data source and cancel subscriptions.
    _locationDataSource.stop();
    _locationSubscription?.cancel();
    _locationHistoryLineOverlay.graphics.clear();
    _locationHistoryPointOverlay.graphics.clear();

    super.dispose();
  }

  @override
  Widget build(BuildContext context) {
    return Scaffold(
      body: SafeArea(
        top: false,
        child: Stack(
          children: [
            Column(
              children: [
                Expanded(
                  // Add a map view to the widget tree and set a controller.
                  child: ArcGISMapView(
                    controllerProvider: () => _mapViewController,
                    onMapViewReady: onMapViewReady,
                  ),
                ),
                Row(
                  mainAxisAlignment: MainAxisAlignment.spaceEvenly,
                  children: [
                    // A button to enable or disable location tracking.
                    ElevatedButton(
                      onPressed: () {
                        setState(() => _enableTracking = !_enableTracking);
                      },
                      child: Text(
                        _enableTracking ? 'Stop Tracking' : 'Start Tracking',
                      ),
                    ),
                  ],
                ),
              ],
            ),
            // Display a progress indicator and prevent interaction until state is ready.
            Visibility(
              visible: !_ready,
              child: SizedBox.expand(
                child: Container(
                  color: Colors.white30,
                  child: const Center(child: CircularProgressIndicator()),
                ),
              ),
            ),
          ],
        ),
      ),
    );
  }

  // The method is called when the map view is ready to be used.
  void onMapViewReady() async {
    // Create a map with the ArcGIS Navigation basemap style.
    final map = ArcGISMap.withBasemapStyle(BasemapStyle.arcGISNavigation);
    // Set the initial viewpoint.
    map.initialViewpoint = Viewpoint.fromCenter(
      ArcGISPoint(
        x: -110.8258,
        y: 32.154089,
        spatialReference: SpatialReference.wgs84,
      ),
      scale: 2e4,
    );
    // Add the map to the map view controller.
    _mapViewController.arcGISMap = map;
    // Add the graphics overlays to the map view.
    _mapViewController.graphicsOverlays.addAll([
      _locationHistoryLineOverlay,
      _locationHistoryPointOverlay,
    ]);
    // Set the renderers for the graphics overlays.
    _locationHistoryLineOverlay.renderer = SimpleRenderer(
      symbol: SimpleLineSymbol(
        color: Colors.red[100]!,
        width: 2.0,
      ),
    );
    _locationHistoryPointOverlay.renderer = SimpleRenderer(
      symbol: SimpleMarkerSymbol(
        color: Colors.red,
        size: 10.0,
      ),
    );
    // Wait for the map to be displayed before starting the location display.
    _mapViewController.onDrawStatusChanged.listen((status) async {
      if (status == DrawStatus.completed &&
          _locationDataSource.status == LocationDataSourceStatus.stopped) {
        await _initLocationDisplay();
      }
    });
    // Set the ready state variable to true to enable the sample UI.
    setState(() => _ready = true);
  }

  // Initialize the location display with the location data source.
  Future<void> _initLocationDisplay() async {
    final locationDisplay = _mapViewController.locationDisplay;
    locationDisplay.dataSource = _locationDataSource;
    locationDisplay.autoPanMode = LocationDisplayAutoPanMode.recenter;
    locationDisplay.useCourseSymbolOnMovement = true;
    await _startLocationDataSource();
  }

  // Start the location data source and listen for location changes.
  Future<void> _startLocationDataSource() async {
    final routeLineJson =
        await rootBundle.loadString('assets/SimulatedRoute.json');
    final routeLine = Geometry.fromJsonString(routeLineJson) as Polyline;
    _locationDataSource.setLocationsWithPolyline(routeLine);

    // Start the location data source.
    try {
      await _locationDataSource.start();
    } on ArcGISException catch (e) {
      if (mounted) {
        showDialog(
          context: context,
          builder: (_) => AlertDialog(
            content: Text(e.message),
          ),
        );
      }
    }

    // Listen for location changes.
    if (_locationDataSource.status == LocationDataSourceStatus.started) {
      _locationSubscription = _locationDataSource.onLocationChanged
          .listen(_handleLdsLocationChange);
    }
  }

  // Handle location changes from the location data source.
  void _handleLdsLocationChange(ArcGISLocation location) {
    if (!_enableTracking) return;
    // Add the location to the location history as a graphic point.
    final point = location.position;
    _locationHistoryPointOverlay.graphics.add(Graphic(geometry: point));
    // Add the location to the location history as a polyline.
    _polylineBuilder.addPoint(point);
    // Visualize the location history polyline on the map.
    _locationHistoryLineOverlay.graphics.clear();
    _locationHistoryLineOverlay.graphics
        .add(Graphic(geometry: _polylineBuilder.toGeometry() as Polyline));
  }
}

Your browser is no longer supported. Please upgrade your browser for the best experience. See our browser deprecation post for more details.