My skill level: Beginner
Code: C# (wpf)
Hardware: Dell Venue 11 Pro tablet (windows 8.1)
I would like to get the current location of my computer via cellular triangulation in coordinates(latitude/longitude). Using the following link as a reference (Getting GPS coordinates on Windows phone 7), I have been attempting to pull the lat/lon coordinates from Windows Location Services. I have verified that Windows Location Services is receiving the coordinates via cell tower triangulation, but every time I run the following code the coordinates are listed as "NaN". Any help here would be greatly appreciated.
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Windows;
using System.Windows.Controls;
using System.Windows.Data;
using System.Windows.Documents;
using System.Windows.Input;
using System.Windows.Media;
using System.Windows.Media.Imaging;
using System.Windows.Navigation;
using System.Windows.Shapes;
using System.Device.Location;
namespace GPS
{
/// <summary>
/// Interaction logic for MainWindow.xaml
/// </summary>
public partial class MainWindow : Window
{
private GeoCoordinateWatcher watcher = new GeoCoordinateWatcher(GeoPositionAccuracy.Default);
public MainWindow()
{
InitializeComponent();
watcher.Start();
LocationMessage();
}
private void LocationMessage()
{
var whereat = watcher.Position.Location;
var Lat = whereat.Latitude.ToString("0.000000");
var Lon = whereat.Longitude.ToString("0.000000");
//optional parameters for future use
whereat.Altitude.ToString();
whereat.HorizontalAccuracy.ToString();
whereat.VerticalAccuracy.ToString();
whereat.Course.ToString();
whereat.Speed.ToString();
MessageBox.Show(string.Format("Lat: {0}\nLon: {1}",Lat,Lon));
}
}
}
If you only need your current position once, and not continous update as you move, you can replace Start
with TryStart
:
if (watcher.TryStart(false, TimeSpan.FromSeconds(3)))
{
LocationMessage();
}
else
{
// Position not found after 3 seconds...
}
Keep in mind that this method returns synchronously, so it is best not to run in on the UI thread.