Find Latitude and Longitude of a System

I'm share the topic of how to find out Latitude and longitude of a system by win form in  C#.

Some points here: 
  1. This only works in .NET Framework 4.0 or later and Windows 7 or later.

  2. The Location API is defined in the System.Device DLL so add a reference to that library. The code includes the following using directive to make using the Location API easier. 
  1. using System.Device.Location;  
  2. private string latitude;  
  3. private string longitute;  
  4. private GeoCoordinateWatcher watcher = new GeoCoordinateWatcher();  
  5. public Form1()  
  6. {  
  7.     InitializeComponent();  
  8. }  
  9. private void button1_Click(object sender, EventArgs e)  
  10. {  
  11.     textBox1.Text = latitude;  
  12.     textBox2.Text = longitute;  
  13. }  
  14. private void Watcher_StatusChanged(object sender, GeoPositionStatusChangedEventArgs e) // Find GeoLocation of Device  
  15.     {  
  16.         try  
  17.         {  
  18.             if (e.Status == GeoPositionStatus.Ready)  
  19.             {  
  20.                 // Display the latitude and longitude.  
  21.                 if (watcher.Position.Location.IsUnknown)  
  22.                 {  
  23.                     latitude = "0";  
  24.                     longitute = "0";  
  25.                 }  
  26.                 else  
  27.                 {  
  28.                     latitude = watcher.Position.Location.Latitude.ToString();  
  29.                     longitute = watcher.Position.Location.Longitude.ToString();  
  30.                 }  
  31.             }  
  32.             else  
  33.             {  
  34.                 latitude = "0";  
  35.                 longitute = "0";  
  36.             }  
  37.         }  
  38.         catch (Exception)  
  39.         {  
  40.             latitude = "0";  
  41.             longitute = "0";  
  42.         }  
  43.     }  
  44. private void Form1_Load(object sender, EventArgs e)  
  45. {  
  46.     watcher = new GeoCoordinateWatcher();  
  47.     // Catch the StatusChanged event.  
  48.     watcher.StatusChanged += Watcher_StatusChanged;  
  49.     // Start the watcher.  
  50.     watcher.Start();  
  51. }  
  52. }  
The accuracy of the location depends on the data available to the computer. If the computer has GPS (many phones and tablets do), this may be quite accurate. If the computer doesn’t have GPS (most desktop systems don’t have it), the API may use wi-fi triangulation or some other method, which may be less accurate.
Ebook Download
View all
Learn
View all