Iris Classon
Iris Classon - In Love with Code

GeoLocation NET 4 and up- requested WinForms example

Here comes a quick and dirty post based of a question I got on Twitter today on how to fetch geolocation in a WinForms app.

I’m sure with enough squinting you can get the location, I just wanted you to work for it. Otherwise address etc. is public information in Sweden, more or less.

I haven’t done this in a while, but if I remember correctly you can do this:

First add the System.Device assembly (Add Reference => Search for ‘Device’)

And make sure location is enabled on your device hehe :D

Then create an instance of the GeoCoordinateWatcher, and add an eventhandler for status changed (and for location changed if you want to). Then start the watcher with watcher.Start()

The reason why we need the eventhandler for the status changes is because if we immediately try to grab the location, or even just our location permissions, it might return false values – probably unknown for permission, NoData for status and so on.

So,

  1. Add assembly

  2. Create object

  3. Add eventhandler

  4. Start the watcher object

  5. Grab location data in the handler when the watcher is ready

There is a lot you can do, setting accuracy and movement threshold, and there is a bunch of other related classes that provide for example speed, or why not the distance from one geolocation to another (both found on GeoLocationclass)?

Ze hacky codez:

public Form1()
{
    InitializeComponent();
 
    _geoWatcher = new GeoCoordinateWatcher();
 
    _geoWatcher.StatusChanged += GeoWatcherOnStatusChanged;
}
 
private GeoCoordinateWatcher _geoWatcher;
 
private void fetchGeo_Click(object sender, EventArgs e)
{
    _geoWatcher.Start();
 
    fetchGeo.Enabled = false;
}
 
private void GeoWatcherOnStatusChanged(object sender, GeoPositionStatusChangedEventArgs e)
{
    if (e.Status != GeoPositionStatus.Ready) return;
 
    GeoPositionPermission allowed = _geoWatcher.Permission;
 
 
    GeoPosition<GeoCoordinate> coordinate = _geoWatcher.Position;
 
    GeoCoordinate deviceLocation = coordinate.Location;
    DateTimeOffset fetchedAt = coordinate.Timestamp;
    reply.Text = string.Format("Lat: {0}, Long: {1}, fetched at: {2}",
        deviceLocation.Latitude,
        deviceLocation.Longitude,
        fetchedAt.DateTime.ToShortTimeString());
}
    
I’ll edit and more later, post written in a hurry by a very tired Iris :)&nbsp;

Comments

Leave a comment below, or by email.

Last modified on 2015-09-21

comments powered by Disqus