Introducing Location in .NET 4.0

The .NET Framework 4.0 RC, which is integrated with Visual Studio 2010, is now available for download. This release of the .NET Framework 4 provides a managed location API in the System.Device.Location namespace that allow .NET developers to access location data from the Windows 7 Sensors & Location platform. If you are familiar with the Location classes from .NET Framework 4 Beta 2, note that this API has been refactored in RC with changes described here.

The managed Location API is built on top of the C++/COM API described in the previous post, so it uses the same mechanism to simplify access to location data by automatically returning data from the best location source it identifies on the computer. However, the methods in the managed API do not correspond exactly to methods in the COM API. The root location object for the .NET Framework 4 Location API, GeoCoordinateWatcher, supplies location data based on latitude and longitude coordinates. Either the Start or TryStart method must be called to initiate the acquisition of data, after which the location data is accessed either by accessing the Position property or by subscribing to the PositionChanged event. In location-aware applications that require continuous updates, such as a navigation application, you’ll want to subscribe to the PositionChanged event. For applications that only require accessing the location once, such as for pre-populating form fields or tagging a file with location metadata, you can get the location from the Position property or by subscribing to the PositionChanged event, getting the location from the first event, and then calling Stop to stop receiving further events. The Status property indicates whether a location sensor is initializing, ready to supply new data, or if no location data is available from any sensor. You can subscribe to the StatusChanged event for status updates.

To get you started using the managed Location API, let’s look at a couple of simple location-aware programs that access the location property or subscribe to updates when the location or location status changes. For each of these examples, you’ll want to add a reference to System.Device in your Visual Studio 2010 project, and add a using statement for the System.Device.Location namespace to your code. The first example gets the location from the Position property, and the second gets the location and status by subscribing to events.

Example 1: Accessing the Position Property

 // Accessing the Position Property
 using System;
 using System.Device.Location; // Add a reference to System.Device.dll
  
 namespace LocationPropertyExample
 {
     class Program
     {
         static void Main(string[] args)
         {
             GetLocationProperty();
         }
  
         static void GetLocationProperty()
         {
             GeoCoordinateWatcher watcher = new GeoCoordinateWatcher();
             
              // Initiate acquisition of location data, so that we 
              // can get location coordinates from the Position property.
              // 1. If we don’t have access to the location sensors, 
              // the user will be prompted with a permission dialog.
              // 2. If we have permissions, following this call, we can 
              //    access location data from the Position property, 
              //    and we'll get PositionChanged events if we have set
              //    up an event handler.
  
             watcher.TryStart(false, // Do not suppress permissions prompt.
                TimeSpan.FromMilliseconds(1000)); // Wait 1000 ms to start.
  
             GeoCoordinate coord = watcher.Position.Location;
  
             if (coord.IsUnknown != true)
             {
                 Console.WriteLine("Lat: {0}, Long: {1}",
                     coord.Latitude,
                     coord.Longitude);
             }
             else
             {
                 Console.WriteLine("Unknown latitude and longitude.");
             }
         }
     }
 }

Example 2: Subscribing to PositionChanged and StatusChanged Events

 // Subscribing to Location Events
 using System;
 using System.Device.Location; // Add a reference to System.Device.dll 
 namespace LocationEventExample
 {
     class Program
     {
         static void Main(string[] args)
         {
             Console.WriteLine("Displaying location updates. Press any key to exit...");
             // GeoCoordinateWatcher is the root object for the .NET 4 Location API
             GeoCoordinateWatcher locationWatcher;
  
             // Initialize the GeoCoordinateWatcher with default accuracy settings
             locationWatcher = new GeoCoordinateWatcher();
  
             // Subscribe to updates when the location changes
             locationWatcher.PositionChanged += new EventHandler<GeoPositionChangedEventArgs<GeoCoordinate>>(locationWatcher_PositionChanged);
             // Subscribe to updates when the status changes.
             // The Status property indicates whether a location sensor is 
             // initializing, ready to supply new data, or if location data is not  
             // available from any sensor. 
             watcher.StatusChanged += new EventHandler<GeoPositionStatusChangedEventArgs> (locationWatcher_StatusChanged);
  
             // Initiate acquisition of location data, so that we 
             // get PositionChanged events.
             // 1. If we don’t have access to the location sensors, the user will 
             //    prompted with a dialog to grant or deny permission.
             // 2. If we have permissions, following this call, we'll be able to 
             //    access location data, and we'll get PositionChanged events if
             //    we have set up an event handler
             locationWatcher.Start();
  
             Console.ReadKey();
         }
  
         static void locationWatcher_PositionChanged(object sender, GeoPositionChangedEventArgs<GeoCoordinate> e)
         {
             // Output the new location coordinate to the console if present
             if (e.Position.Location != GeoCoordinate.Unknown)
             {
                 Console.WriteLine(
                     "Latitude:  " + e.Position.Location.Latitude.ToString() +
                     " Longitude: " + e.Position.Location.Longitude.ToString());
             }
         }
        static void locationWatcher_StatusChanged(object sender, GeoPositionStatusChangedEventArgs e)
        {
             switch (e.Status)
             {
                 case GeoPositionStatus.Initializing:
                     Console.WriteLine("Working on location fix");
                     break;
  
                 case GeoPositionStatus.Ready:
                     Console.WriteLine("Have location");
                     break;
  
                 case GeoPositionStatus.NoData:
                     Console.WriteLine("No data");
                     break;
  
                 case GeoPositionStatus.Disabled:
                     Console.WriteLine("Disabled");
                     break;
             }
        }
     }
 }

-- Sensor & Location Platform Team

This posting is provided "AS IS" with no warranties and confers no rights.