Skip to content

Display device location with NMEA data sources

View inMAUIWPFWinUIView on GitHubSample viewer app

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 // 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; using System.Collections.Generic; using System.IO; using System.Linq; using System.Text; using System.Threading; using System.Threading.Tasks; using System.Timers; using System.Windows;  namespace ArcGIS.WPF.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  {  private NmeaLocationDataSource _nmeaSource;   public LocationWithNMEA()  {  InitializeComponent();  Initialize();  }   private void Initialize()  {  // Add event handler for when this sample is unloaded.  Unloaded += SampleUnloaded;   // 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.  string nmeaMockDataPath = DataManager.GetDataFolder("d5bad9f4fee9483791e405880fb466da", "Redlands.nmea");   // Create the NMEA data source.  _nmeaSource = NmeaLocationDataSource.FromStreamCreator((datasource) => Task.FromResult<Stream>(new SimulatedNmeaStream(nmeaMockDataPath)));  // To create a NmeaLocationDataSource for a bluetooth device, use the `FromBluetooth` constructor. https://developers.arcgis.com/net/api-reference/api/netwin/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/netwin/Esri.ArcGISRuntime/Esri.ArcGISRuntime.Location.NmeaLocationDataSource.FromSerialPort.html   // Create an event handler to update the UI when the location changes.  _nmeaSource.SatellitesChanged += SatellitesChanged;  _nmeaSource.LocationChanged += LocationChanged;  _nmeaSource.SentenceReceived += UpdateNmeaMessageLabel;   MyMapView.LocationDisplay.DataSource = _nmeaSource;  }   private void UpdateNmeaMessageLabel(object sender, string message)  {  if (message.StartsWith("$GPRMC")) // Display the latest RMC message  {  Dispatcher.BeginInvoke(new Action(() => NmeaMessageLabel.Content = message ));  }  }   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);  }   Dispatcher.BeginInvoke(new Action(() =>  {  // Show the status information in the UI.  CountLabel.Content = $"Satellite count: {infos.Count}";  SatellitesLabel.Content = $"Satellites: {string.Join(", ", uniqueSatelliteIds)}";  SystemLabel.Content = $"System: {infos.First().System}";  }));  }   private void LocationChanged(object sender, Location loc)  {  Dispatcher.BeginInvoke(new Action(() =>  {  // Show the status information in the UI.  AccuracyLabel.Content = $"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, RoutedEventArgs e)  {  _nmeaSource.StartAsync();  AccuracyLabel.Content = string.Empty;  }   private void ResetClick(object sender, RoutedEventArgs e)  {  _nmeaSource.StopAsync();   // Reset the labels.  AccuracyLabel.Content = "Simulation reset.";  CountLabel.Content = string.Empty;  SatellitesLabel.Content = string.Empty;  SystemLabel.Content = string.Empty;  NmeaMessageLabel.Content = string.Empty;  }   private void SampleUnloaded(object sender, RoutedEventArgs e)  {  // Stop the location data source.  MyMapView.LocationDisplay?.DataSource?.StopAsync();  }  }   /*  * 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 simulate the datastream from a file like below  */   public class SimulatedNmeaStream : Stream  {  // The default interval in milliseconds between bursts of NMEA data.  private const int DefaultInterval = 1000;   private readonly System.Timers.Timer _timer;   private readonly StreamReader _sr;   private int _pendingBursts = 0;   public SimulatedNmeaStream(string file)  {  // Populate an array with all of the mock NMEA data.  _sr = new StreamReader(file);  _timer = new System.Timers.Timer(DefaultInterval);  _timer.Elapsed += TimerElapsed;  _timer.Start();  }   private void TimerElapsed(object sender, ElapsedEventArgs e) => _pendingBursts++;   protected override void Dispose(bool disposing)  {  if (disposing)  {  // Dispose of the timer and stream.  _timer.Stop();  _timer.Dispose();  _sr.Dispose();  }  base.Dispose(disposing);  }   #region Implementation of a custom System.IO.Stream   public override int Read(byte[] buffer, int offset, int count)  {  if (_pendingBursts == 0)  // Nothing in the buffer to read.  return 0;   // Read all the pending bursts of data until we fill up the buffer.  var start = _sr.BaseStream.Position;  StringBuilder sb = new StringBuilder();  while (sb.Length < count && !_sr.EndOfStream && _pendingBursts > 0)  {  string line = _sr.ReadLine();  // In this sample we pause the burst of messages for each GGA message to simulate the break in the nmea stream on a receiver.  if (line.StartsWith("$GPGGA,") && Interlocked.Decrement(ref _pendingBursts) == 0)  {  break;  }  sb.AppendLine(line);  }   if (sb.Length == 0)  return 0;  byte[] data = System.Text.Encoding.UTF8.GetBytes(sb.ToString());  count = Math.Min(count, data.Length);  Array.Copy(data, 0, buffer, offset, count);  // Move the stream position forward only the amount of data we read.  _sr.BaseStream.Seek(start + count, SeekOrigin.Begin);  return count;  }   public override bool CanRead => true;   public override bool CanSeek => false;   public override bool CanWrite => false;   public override long Length => -1;   public override long Position { get => _sr.BaseStream.Position; set => throw new NotImplementedException(); }   public override void Flush() => throw new NotImplementedException();   public override long Seek(long offset, SeekOrigin origin) => throw new NotImplementedException();   public override void SetLength(long value) => throw new NotImplementedException();   public override void Write(byte[] buffer, int offset, int count) => throw new NotImplementedException();   #endregion  } }

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