Show device location with NMEA data sources

View on GitHub

Parse NMEA sentences and use the results to show device location on the map.

Image of show device location with NMEA data sources

Use case

NMEA sentences can be retrieved from GPS receivers and parsed into a series of coordinates with additional information. Devices without a built-in GPS receiver can retrieve NMEA sentences by using a separate GPS dongle, commonly connected via Bluetooth or through a serial port.

The NMEA location data source allows for detailed interrogation of the information coming from the GPS receiver. For example, allowing you to report the number of satellites in view.

How to use the sample

Tap the "Start" button to start a simulated NMEA data provider and the NmeaLocationDataSource. Tap "Recenter" to recenter the location display. Tap "Reset" to reset the location display.

How it works

  1. A simulated NMEA data source parses an NMEA string into sentences and provides that data as a stream.
  2. Create a NmeaLocationDataSource and push the NMEA sentences from the stream with NmeaLocationDataSource.pushData().
  3. Set the NmeaLocationDataSource to the location display's data source.
  4. Start the location data source to begin receiving location and satellite updates.

Relevant API

  • ArcGISLocation
  • LocationDisplay
  • NmeaLocationDataSource
  • NmeaSatelliteInfo

About the data

A string of NMEA sentences is used to initialize a SimulatedNmeaDataSource object. This simulated data source provides NMEA data periodically, and allows the sample to be used on devices without a GPS dongle that produces NMEA data.

The route taken in this sample features a 2-minute driving trip around Redlands, CA.

Additional information

Below is a list of protocol strings for commonly used GNSS external accessories. Please refer to the ArcGIS Field Maps documentation for model and firmware requirements.

  • com.amanenterprises.nmeasource
  • com.bad-elf.gps
  • com.dualav.xgps150
  • com.eos-gnss.positioningsource
  • com.garmin.pvt
  • com.geneq.sxbluegpssource
  • com.junipersys.geode
  • com.leica-geosystems.zeno.gnss
  • com.searanllc.serial
  • com.trimble.correction, com.trimble.command (1)

(1) Some Trimble models requires a proprietary SDK for NMEA output.

Tags

dongle, GPS, history, navigation, NMEA, real-time, trace

Sample Code

show_device_location_with_nmea_data_sources.dartshow_device_location_with_nmea_data_sources.dartsimulated_nmea_data_source.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
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
// Copyright 2025 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 'dart:convert';

import 'package:arcgis_maps/arcgis_maps.dart';
import 'package:arcgis_maps_sdk_flutter_samples/common/common.dart';
import 'package:arcgis_maps_sdk_flutter_samples/samples/show_device_location_with_nmea_data_sources/simulated_nmea_data_source.dart';
import 'package:flutter/material.dart';

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

  @override
  State<ShowDeviceLocationWithNmeaDataSources> createState() =>
      _ShowDeviceLocationWithNmeaDataSourcesState();
}

class _ShowDeviceLocationWithNmeaDataSourcesState
    extends State<ShowDeviceLocationWithNmeaDataSources>
    with SampleStateSupport {
  // Create a controller for the map view.
  final _mapViewController = ArcGISMapView.createController();

  // Create the NMEA location data source.
  final _locationDataSource = NmeaLocationDataSource();

  // Subscriptions to location data source events and members to keep current data.
  StreamSubscription? _locationSubscription;
  ArcGISLocation? _currentNmeaLocation;
  StreamSubscription? _satelliteSubscription;
  var _currentSatelliteInfos = <NmeaSatelliteInfo>[];

  // Simulated NMEA data provider members.
  SimulatedNmeaDataSource? _nmeaDataSimulator;
  StreamSubscription? _nmeaDataSubscription;

  // Enable or disable the Recenter button.
  var _enableRecenter = false;
  StreamSubscription? _autopanSubscription;

  // A flag for when the NmeaLocationDataSource is running.
  var _locationDataSourceRunning = false;

  // A flag for when the map view is ready and controls can be used.
  var _ready = false;

  @override
  void dispose() {
    // Cancel all the subscriptions.
    _nmeaDataSubscription?.cancel();
    _autopanSubscription?.cancel();
    _locationSubscription?.cancel();
    _satelliteSubscription?.cancel();

    super.dispose();
  }

  @override
  Widget build(BuildContext context) {
    return Scaffold(
      body: SafeArea(
        top: false,
        left: false,
        right: 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: [
                    // Start the Location Data Source.
                    ElevatedButton(
                      onPressed:
                          _locationDataSource.status ==
                                  LocationDataSourceStatus.stopped
                              ? _startDataSource
                              : null,
                      child: const Text('Start'),
                    ),
                    // Recenter the map on the blue dot.
                    ElevatedButton(
                      onPressed:
                          _enableRecenter
                              ? () {
                                // Set the autoPanMode to recenter.
                                _mapViewController.locationDisplay.autoPanMode =
                                    LocationDisplayAutoPanMode.recenter;
                              }
                              : null,
                      child: const Text('Recenter'),
                    ),
                    // Stop and reset the location data source.
                    ElevatedButton(
                      onPressed:
                          _locationDataSourceRunning ? _stopDataSource : null,
                      child: const Text('Reset'),
                    ),
                  ],
                ),
              ],
            ),
            // Widget to show top details.
            NmeaLocationDetails(
              nmeaLocation: _currentNmeaLocation,
              nmeaSatelliteInfos: _currentSatelliteInfos,
            ),
            // Display a progress indicator and prevent interaction until state is ready.
            LoadingIndicator(visible: !_ready),
          ],
        ),
      ),
    );
  }

  Future<void> onMapViewReady() async {
    // Create a map and set it to the MapView.
    final map = ArcGISMap.withBasemapStyle(BasemapStyle.arcGISTopographic);
    _mapViewController.arcGISMap = map;

    // Use the NMEA location data source as the data source for the map.
    _mapViewController.locationDisplay.dataSource = _locationDataSource;

    // Subscribe to the location stream of the location data source.
    _locationSubscription = _locationDataSource.onLocationChanged.listen((
      location,
    ) {
      setState(() => _currentNmeaLocation = location);
    });

    // Subscribe to the location data source's satellite changed stream.
    _satelliteSubscription = _locationDataSource.onSatellitesChanged.listen((
      satelliteInfos,
    ) {
      setState(() => _currentSatelliteInfos = satelliteInfos);
    });

    // Set the autoPanMode to recenter and listen for any changes.
    _mapViewController.locationDisplay.autoPanMode =
        LocationDisplayAutoPanMode.recenter;
    _autopanSubscription = _mapViewController
        .locationDisplay
        .onAutoPanModeChanged
        .listen((autoPanMode) {
          setState(() {
            // Activates/deactivates the Recenter button based on the new auto pan mode.
            _enableRecenter =
                autoPanMode != LocationDisplayAutoPanMode.recenter;
          });
        });

    // Set the ready state variable to true to enable the UI.
    setState(() => _ready = true);
  }

  Future<void> _startDataSource() async {
    // Create new instance of the NmeaSourceSimulator.
    _nmeaDataSimulator ??= SimulatedNmeaDataSource();

    // Subscribe to the simulator data.
    _nmeaDataSubscription ??= _nmeaDataSimulator!.nmeaMessages.listen((
      nmeaDataString,
    ) {
      final nmeaData = utf8.encoder.convert(nmeaDataString);
      _locationDataSource.pushData(nmeaData);
    });

    // Start the NMEALocationDataSource.
    await _locationDataSource.start();

    // Set the running state to enable the Reset button.
    setState(() => _locationDataSourceRunning = true);
  }

  Future<void> _stopDataSource() async {
    // Stop the location data source.
    await _locationDataSource.stop();

    // Cancel simulator subscription and remove reference to NMEA source
    // simulator and subscription.
    await _nmeaDataSubscription?.cancel();
    _nmeaDataSubscription = null;
    _nmeaDataSimulator = null;

    // Update the affected state variables.
    setState(() {
      _currentNmeaLocation = null;
      _currentSatelliteInfos = <NmeaSatelliteInfo>[];
      _locationDataSourceRunning = false;
    });
  }
}

// Widget that displays current location accuracy and NMEA satellite information.
class NmeaLocationDetails extends StatelessWidget {
  const NmeaLocationDetails({
    required this.nmeaLocation,
    required this.nmeaSatelliteInfos,
    super.key,
  });

  final ArcGISLocation? nmeaLocation;
  final List<NmeaSatelliteInfo> nmeaSatelliteInfos;

  @override
  Widget build(BuildContext context) {
    // Create list of child Widgets that will be shown in a Column.
    final children = <Widget>[];

    // If there is no location object, show placeholder text. Otherwise, compose
    // accuracy data string.
    final accuracy =
        nmeaLocation == null
            ? 'Accuracy will be shown here.'
            : 'Accuracy: Horizontal: ${nmeaLocation!.horizontalAccuracy.toStringAsFixed(3)}, Vertical: ${nmeaLocation!.verticalAccuracy.toStringAsFixed(3)}';
    children.add(Text(accuracy));

    // If there are no satellites, show placeholder text. Otherwise, compose the
    // Strings for satellite count, navigation systems, and IDs.
    if (nmeaSatelliteInfos.isEmpty) {
      children.add(const Text('Satellite information will be shown here.'));
    } else {
      final navigationSystems = <String>{};
      final satelliteIds = <int>[];

      for (final satellite in nmeaSatelliteInfos) {
        // Navigation system.
        navigationSystems.add(satellite.system.label);
        // Satellite Ids.
        satelliteIds.add(satellite.id);
      }

      children.add(
        Text('${nmeaSatelliteInfos.length} satellites are in view.'),
      );
      children.add(Text('System(s): ${navigationSystems.join(', ')}'));
      children.add(Text('IDs: ${satelliteIds.join(', ')}'));
    }

    // Build and return the Widget.
    return Column(
      children: [
        ColoredBox(
          color: const Color.fromARGB(200, 255, 255, 255),
          child: SafeArea(
            left: false,
            right: false,
            child: SizedBox(
              width: MediaQuery.sizeOf(context).width,
              child: Padding(
                padding: const EdgeInsets.symmetric(
                  horizontal: 10,
                  vertical: 5,
                ),
                child: Column(
                  crossAxisAlignment: CrossAxisAlignment.start,
                  children: children,
                ),
              ),
            ),
          ),
        ),
      ],
    );
  }
}

// Extension on NmeaGnssSystem to provide a readable label.
extension on NmeaGnssSystem {
  String get label {
    switch (name) {
      case 'gps':
        return 'The Global Positioning System';
      case 'glonass':
        return 'The Russian Global Navigation Satellite System';
      case 'galileo':
        return 'The European Union Global Navigation Satellite System';
      case 'bds':
        return 'The BeiDou Navigation Satellite System';
      case 'qzss':
        return 'The Quasi-Zenith Satellite System';
      case 'navIc':
        return 'The Navigation Indian Constellation';
      default:
        return 'Unknown GNSS type';
    }
  }
}

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