So you want to write an application in .NET that’s location-aware? Let’s start with a code sample (console application) that will show you how to use a GeoLocationProvider to respond to location updates, and print those updates out to the console.
In order to compile and run this code, you’ll need Visual Studio 2010 installed, and you’ll need to create a new console application project. If you paste this code into your Program.cs, and then add a reference to System.Device.dll, you should be ready to go.
// This namespace is where you'll find the location API in .NET 4
// **Note that you'll have to add a reference to System.Device.dll first
static void Main(string args)
Console.WriteLine("Outputting location updates, press any key to exit...");
// The LocationWatcher object will monitor location updates
// and output them to the console
LocationWatcher watcher = new LocationWatcher();
// Root object for the .NET 4 Location API
// we'll hang on to a reference for the lifetime of
// the LocationWatcher object
private GeoLocationProvider provider;
// Initialize our private member
this.provider = new GeoLocationProvider();
// Subscribe to updates when our location changes
this.provider.LocationChanged += new
// When we call Start(), two things happen
// 1. If we don't have permissions to access the location sensor(s),
// the user will be presented with a dialog where they can grant
// 2. If we have permissions, following this call, we'll be able to
// access location data, and we'll get LocationChanged events if
// we have setup an event handler
void provider_LocationChanged(object sender, GeoLocationChangedEventArgs e)
// Output the new location coordinate to the console if present
if (e.Location.Coordinate != GeoCoordinate.Unknown)
"Latitude: " + e.Location.Coordinate.Latitude.ToString() +
" Longitude: " + e.Location.Coordinate.Longitude.ToString());
If you have a Windows 7 supported GPS, WAN card, or other provider (such as a software-based lookup provider) attached/installed, you will see output that will look like the following:
When we create our LocationWatcher object, it in turn creates an instance of a GeoLocationProvider, subscribes to the LocationChanged event, starts the provider, and prints out location updates to the console from the LocationChanged event handler.
This is a simple example of using location data with .NET 4. In future blog posts, we’ll explore other parts of this API, and see what else we can do with it.
**Note: There will be some changes in this object model coming for RC, so make sure to check back here if you are writing .NET 4 Location apps