Use the Location API to find the computer’s latitude and longitude in C#

[Location API]

Before you try this, note the following caveats:

  • This only works in .NET Framework 4.0 or later and Windows 7 or later.
  • The operating system can grant or deny access to location information for a program. If the application is not allowed to use location services, the watcher’s StatusChanged event used by this program never fires.
  • The CivicAddressResolver class’s ResolveAddress method has not yet been implemented by Microsoft so you can’t convert this program into one that gets the location’s street address.

If you haven’t given up yet and warped to another web page, here’s how the program works.

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.

using System.Device.Location;

When the program starts, it executes the following code.

// The coordinate watcher.
private GeoCoordinateWatcher Watcher = null;

// Create and start the watcher.
private void Form1_Load(object sender, EventArgs e)
{
    // Create the watcher.
    Watcher = new GeoCoordinateWatcher();

    // Catch the StatusChanged event.
    Watcher.StatusChanged += Watcher_StatusChanged;

    // Start the watcher.
    Watcher.Start();
}

The code declares a GeoCoordinateWatcher. The Form’s Load event handler creates the watcher and adds an event handler to its StatusChanged event. It then calls the watcher’s Start method to make start it asynchronously.

The TryStart method is supposed to make the object start and block until it is ready for business so the program could avoid using an event handler, but I couldn’t get it to work on my system. Post a comment if you figure out how to make TryStart work.

The watcher starts and raises its StatusChanged event to tell the program about its progress. The following event handler catches that event. As I mentioned in the caveats, this event isn’t raised if the application doesn’t have permission to access the computer’s location.

// The watcher's status has change. See if it is ready.
private void Watcher_StatusChanged(object sender,
    GeoPositionStatusChangedEventArgs e)
{
    if (e.Status == GeoPositionStatus.Ready)
    {
        // Display the latitude and longitude.
        if (Watcher.Position.Location.IsUnknown)
        {
            txtLat.Text = "Cannot find location data";
        }
        else
        {
            GeoCoordinate location =
                Watcher.Position.Location;
            txtLat.Text = location.Latitude.ToString();
            txtLong.Text = location.Longitude.ToString();
        }
    }
}

If the watcher’s status has changed to Ready, the program checks Watcher.Position.Location.IsUnknown to see if the watcher found the computer’s location. If it did not find the computer’s location, the code displays a message in the latitude TextBox.

If the watcher did find the computer’s location, the code uses the watcher’s Position.Location property to display the computer’s latitude and longitude.

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.


Download Example   Follow me on Twitter   RSS feed   Donate




This entry was posted in internet, miscellany, system and tagged , , , , , , , , , , , , , . Bookmark the permalink.

4 Responses to Use the Location API to find the computer’s latitude and longitude in C#

  1. Rajveer Singh says:

    But this point not show exact location in google map

    • RodStephens says:

      You should read the last paragraph again. If the computer has GPS, it may provide a good location. If it doesn’t, you may not get a great result. I just tried it with no GPS, but I’m at a car dealership and the location services knew that I was at the dealership. It was about 50 feet from my actual location.

      Overall I wouldn’t rely on this method to find exact position unless you know that you have a GPS in the computer. But it should give you useful results for things like knowing what neighborhood you’re in or checking the weather forecast for your area.

  2. Eli Geller says:

    Thanks for the quick and easy to follow example!

Leave a Reply

Your email address will not be published. Required fields are marked *