Sep 212015
 
 September 21, 2015  Posted by at 3:11 pm C# & F#, Windows Forms

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.

geoLocationInWinforms4

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’)

geoLocationInWinforms

And make sure location is enabled on your device hehe 😀

geoLocationInWinforms3

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.

geoLocationInWinforms2

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 GeoLocation class)?

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.Readyreturn;
 
    GeoPositionPermission allowed = _geoWatcher.Permission;
 
 
    GeoPosition<GeoCoordinatecoordinate = _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 🙂

 

Sorry, the comment form is closed at this time.