Finding the computer’s latitude and longitude in C#

Finding the computer's position is possible even if it doesn't have a built in GPS since it's possible to get a position using Wi-Fi triangulation.  Using the .NET Framework 4+ you can add a reference to the System.Device.dll that contains the System.Device.Location.GeoCoordinateWatcher class that let you retrieve the latitude and longitude.  Here's a quick test I did in a console app:

using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Device.Location;

namespace ConsoleApplicationGeo
{
	class Program
	{
		private static GeoCoordinateWatcher Watcher;

		static void Main(string[] args)
		{
			Watcher = new GeoCoordinateWatcher();
			Watcher.StatusChanged += Watcher_StatusChanged;
			Watcher.Start();

			Console.ReadLine();

		}

		static void Watcher_StatusChanged(object sender, GeoPositionStatusChangedEventArgs e)
		{
			if (e.Status == GeoPositionStatus.Ready)
			{
				if (Watcher.Position.Location.IsUnknown)
				{
					Console.Write("Cannot find location");
				}
				else
				{
					Console.WriteLine("Lat: " + Watcher.Position.Location.Latitude.ToString());
					Console.WriteLine("Lon: " + Watcher.Position.Location.Longitude.ToString());
				}
			}
		}

	}
}
blog comments powered by Disqus

Page List

Month List