Display device location with NMEA data sources

View inMAUIWPFWinUIView on GitHub

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

Image of NMEA location data source

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 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 "Start" to parse the NMEA sentences into a simulated location data source, and initiate the location display. Tap "Recenter" to recenter the location display. Tap "Reset" to reset the location display.

How it works

  1. Load NMEA sentences from a local file.
  2. Parse the NMEA sentence strings, and push data into NmeaLocationDataSource.
  3. Set the NmeaLocationDataSource to the location display's data source.
  4. Start the location display to begin receiving location and satellite updates.

Relevant API

  • Location
  • LocationDisplay
  • NmeaLocationDataSource
  • NmeaSatelliteInfo

About the data

A list of NMEA sentences is used to initialize a to simulate a stream of NMEA data. 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.

Supported by this sample

  • com.bad-elf.gps
  • com.eos-gnss.positioningsource
  • com.geneq.sxbluegpssource

Others

  • com.amanenterprises.nmeasource
  • com.dualav.xgps150
  • com.garmin.pvt
  • com.junipersys.geode
  • com.leica-geosystems.zeno.gnss
  • com.searanllc.serial
  • com.trimble.correction, com.trimble.command (1)

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

Tags

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

Sample Code

LocationWithNMEA.xaml.csLocationWithNMEA.xaml.csLocationWithNMEA.xaml
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
// Copyright 2022 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 ArcGIS.Samples.Managers;
using Esri.ArcGISRuntime.Geometry;
using Esri.ArcGISRuntime.Location;
using Esri.ArcGISRuntime.Mapping;
using Esri.ArcGISRuntime.UI;
using System.Timers;
using Location = Esri.ArcGISRuntime.Location.Location;
using Timer = System.Timers.Timer;

namespace ArcGIS.Samples.LocationWithNMEA
{
    [ArcGIS.Samples.Shared.Attributes.Sample(
        name: "Display device location with NMEA data sources",
        category: "Location",
        description: "Parse NMEA sentences and use the results to show device location on the map.",
        instructions: "Tap \"Start\" to parse the NMEA sentences into a simulated location data source, and initiate the location display. Tap \"Recenter\" to recenter the location display. Tap \"Reset\" to reset the location display.",
        tags: new[] { "GNSS", "GPS", "NMEA", "RTK", "dongle", "history", "navigation", "real-time", "trace" })]
    [ArcGIS.Samples.Shared.Attributes.OfflineData("d5bad9f4fee9483791e405880fb466da")]
    public partial class LocationWithNMEA : ContentPage, IDisposable
    {
        private NmeaLocationDataSource _nmeaSource;

        private NMEAStreamSimulator _simulatedNMEADataSource;

        public LocationWithNMEA()
        {
            InitializeComponent();
            _ = Initialize();
        }

        private async Task Initialize()
        {
            // Create the map.
            MyMapView.Map = new Map(BasemapStyle.ArcGISNavigation);
            MyMapView.SetViewpoint(new Viewpoint(new MapPoint(-117.191, 34.0306, SpatialReferences.Wgs84), 100000));

            // Create the data simulation using stored mock data.
            _simulatedNMEADataSource = new NMEAStreamSimulator(6.0);
            _simulatedNMEADataSource.NmeaMessageChanged += UpdateNmeaMessageLabel;

            // Create the NMEA data source.
            _nmeaSource = new NmeaLocationDataSource(SpatialReferences.Wgs84);

            // Android and WinUI:
            // To create a NmeaLocationDataSource for a bluetooth device, use the `FromBluetooth` constructor. https://developers.arcgis.com/net/api-reference/api/android/Esri.ArcGISRuntime/Esri.ArcGISRuntime.Location.NmeaLocationDataSource.FromBluetooth.html
            // To create a NmeaLocationDataSource from a serial port, use the `FromSerialPort` constructor. https://developers.arcgis.com/net/api-reference/api/android/Esri.ArcGISRuntime/Esri.ArcGISRuntime.Location.NmeaLocationDataSource.FromSerialPort.html

            // iOS:
            // When using an NMEA device on iOS, use the `NmeaLocationDataSource.FromAccessory` constructor. https://developers.arcgis.com/net/api-reference/api/ios/Esri.ArcGISRuntime/Esri.ArcGISRuntime.Location.NmeaLocationDataSource.FromAccessory.html

            // Set the location data source to use the stream from the simulator.
            Stream messageStream = _simulatedNMEADataSource.MessageStream;
            _nmeaSource.NmeaDataStream = messageStream;

            // Create an event handler to update the UI when the location changes.
            _nmeaSource.SatellitesChanged += SatellitesChanged;
            _nmeaSource.LocationChanged += LocationChanged;

            // Start the location data source.
            try
            {
                await MyMapView.Map.LoadAsync();
                MyMapView.LocationDisplay.DataSource = _nmeaSource;
                await _nmeaSource.StartAsync();
            }
            catch (Exception ex)
            {
                await Application.Current.MainPage.DisplayAlert(ex.Message.GetType().Name, ex.Message, "OK");
            }
        }

        private void UpdateNmeaMessageLabel(object sender, NmeaMessageEventArgs e)
        {
            Microsoft.Maui.ApplicationModel.MainThread.BeginInvokeOnMainThread(() =>
            {
                NmeaMessageLabel.Text = e.NmeaMessage;
            });
        }

        private void SatellitesChanged(object sender, IReadOnlyList<NmeaSatelliteInfo> infos)
        {
            // Check for any satellite info.
            if (infos.Count == 0) return;

            // Get all of the satellite Id's from the satellite infos.
            SortedSet<int> uniqueSatelliteIds = new SortedSet<int>();
            foreach (var info in infos)
            {
                uniqueSatelliteIds.Add(info.Id);
            }

            Microsoft.Maui.ApplicationModel.MainThread.BeginInvokeOnMainThread(() =>
            {
                // Show the status information in the UI.
                CountLabel.Text = $"Satellite count: {infos.Count}";
                SatellitesLabel.Text = $"Satellites: {string.Join(", ", uniqueSatelliteIds)}";
                SystemLabel.Text = $"System: {infos.First().System}";
            });
        }

        private void LocationChanged(object sender, Location loc)
        {
            Microsoft.Maui.ApplicationModel.MainThread.BeginInvokeOnMainThread(() =>
            {
                // Show the status information in the UI.
                AccuracyLabel.Text = $"Accuracy: Horizontal {string.Format("{0:0.00}", loc.HorizontalAccuracy)} meters, Vertical  {string.Format("{0:0.00}", loc.VerticalAccuracy)} meters";

                // Recenter on the new location.
                MyMapView.LocationDisplay.AutoPanMode = LocationDisplayAutoPanMode.Recenter;
            });
        }

        private void StartClick(object sender, EventArgs e)
        {
            _simulatedNMEADataSource.Start();
            AccuracyLabel.Text = string.Empty;
        }

        private void RecenterClick(object sender, EventArgs e)
        {
            MyMapView.LocationDisplay.AutoPanMode = Esri.ArcGISRuntime.UI.LocationDisplayAutoPanMode.Recenter;
        }

        private void ResetClick(object sender, EventArgs e)
        {
            _simulatedNMEADataSource.Stop();
            _simulatedNMEADataSource.Reset();

            // Reset the labels.
            AccuracyLabel.Text = "Simulation reset.";
            CountLabel.Text = string.Empty;
            SatellitesLabel.Text = string.Empty;
            SystemLabel.Text = string.Empty;
            NmeaMessageLabel.Text = string.Empty;
        }

        public void Dispose()
        {
            // Stop the location data source.
            MyMapView.LocationDisplay?.DataSource?.StopAsync();
            _simulatedNMEADataSource?.Dispose();
        }
    }

    /*
     * This class uses mock data (an edited recording of a real NMEA data stream) to simulate live NMEA data and create a stream.
     * For NMEA location data sources created from a Bluetooth device or serial input, you may not need to create your own stream.
     * For any other case, you can write the data to a memory stream like below.
     */

    public class NMEAStreamSimulator : IDisposable
    {
        private Timer _timer;

        public Stream MessageStream;

        private int _lineCounter = 0;
        private const int DefaultInterval = 1000;

        private string[] _nmeaStrings;

        public event EventHandler<NmeaMessageEventArgs> NmeaMessageChanged;

        public NMEAStreamSimulator(double speed = 1.0)
        {
            _timer = new Timer(DefaultInterval / speed);

            // Populate an array with all of the mock NMEA data.
            string nmeaMockDataPath = DataManager.GetDataFolder("d5bad9f4fee9483791e405880fb466da", "Redlands.nmea");
            _nmeaStrings = File.ReadAllText(nmeaMockDataPath).Split('\n');

            // Create a data stream for the `NmeaLocationDataSource` to use.
            MessageStream = new MemoryStream();

            _timer.Elapsed += TimerElapsed;
        }

        public void Start()
        {
            _timer.Start();
        }

        public void Stop()
        {
            _timer.Stop();
        }

        public void Reset()
        {
            _timer.Stop();
            _lineCounter = 0;
        }

        private void TimerElapsed(object sender, ElapsedEventArgs e)
        {
            // Get the next NMEA string and append return and newline characters to it.
            string nmeaString = $"{_nmeaStrings[_lineCounter]}\r\n";

            NmeaMessageChanged?.Invoke(this, new NmeaMessageEventArgs { NmeaMessage = nmeaString });

            // Check if the start of a new location message.
            if (nmeaString.StartsWith("$GPGGA"))
            {
                // Flush any existing NMEA data from the stream.
                MessageStream.Flush();
            }

            // Write the string to the stream.
            byte[] data = System.Text.Encoding.UTF8.GetBytes(nmeaString);
            MessageStream.Write(data, 0, data.Length);

            // Increment the line counter.
            _lineCounter = (_lineCounter + 1) % _nmeaStrings.Length;
        }

        public void Dispose()
        {
            // Dispose of the timer and stream.
            _timer.Stop();
            _timer.Dispose();
            MessageStream.Dispose();
        }
    }

    public class NmeaMessageEventArgs : EventArgs
    {
        public string NmeaMessage { get; set; }
    }
}

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