共用方式為


How to use the .NET Location API for Windows Phone 8

[ This article is for Windows Phone 8 developers. If you’re developing for Windows 10, see the latest documentation. ]

Note

Windows Phone 8 has a new Windows Phone Runtime API for creating location-aware apps. The content in this topic applies to the .NET Location API which was introduced in Windows Phone OS 7.0 and which is still fully supported. For information on which API set is right for your application, see Location for Windows Phone 8.

This topic shows how you can initialize the Location Service, handle changes in the service’s status, and obtain location data. To read about and download a sample application that uses the Location Service, see Location Service Sample.

This topic contains the following sections.

Referencing the Location Service

To use the Location Service managed APIs, you must first add a reference to System.Device.dll to your application.

To add a reference to the Location Service DLL

  1. Open a new or existing Windows Phone solution in Visual Studio.

  2. From the Project menu, select Add Reference….

  3. On the .NET tab, select the component name “System.Device” and click OK.

Next, add a using directive to the top of the .xaml.cs file for the page that is going to use the Location Service.

using System.Device.Location;

Add a variable declaration for the GeoCoordinateWatcher object that you will use to access the Location Service. Give the variable class scope so that it will stay in memory as long as the page is displayed.

public partial class MainPage : PhoneApplicationPage
{
  GeoCoordinateWatcher watcher;

Implementing a Location-based Application

The following code illustrates how to obtain data from the Location Service.

To obtain data from the Location Service

  1. Use the Start method of the GeoCoordinateWatcher object to start the acquisition of data from the Location Service. You can call this as soon as the page is loaded. However, you can allow the user greater control over the power consumption of the application by allowing the user to choose when to start the service. For example, you could start the service in the handler for a button click event.

    // Click the event handler for the “Start Location” button.
    private void startLocationButton_Click(object sender, RoutedEventArgs e)
    {
      // The watcher variable was previously declared as type GeoCoordinateWatcher. 
      if (watcher == null)
      {
        watcher = new GeoCoordinateWatcher(GeoPositionAccuracy.High); // using high accuracy
        watcher.MovementThreshold = 20; // use MovementThreshold to ignore noise in the signal
    
  2. Add event handlers for the StatusChanged and PositionChanged events.

        watcher.StatusChanged += new EventHandler<GeoPositionStatusChangedEventArgs>(watcher_StatusChanged);
        watcher.PositionChanged += new EventHandler<GeoPositionChangedEventArgs<GeoCoordinate>>(watcher_PositionChanged);
      }
    
  3. Now, start the Location Service. This version of the Start()()() method starts acquisition of data from the service asynchronously, so the user can continue to use your application while the application service attempts to start and obtain data.

      watcher.Start();
    } // End of the Start button Click handler.
    
  4. Implement the StatusChanged event handler. This event is raised whenever the status of the Location Service changes. The GeoPositionStatus enumeration that is passed in the GeoPositionStatusChangedEventArgs object, tells you the current status of the service. You can use it to enable location-based functionality in your application and to communicate the current state of the service to the user. If the status of the service is Disabled, you can check the Permission property to see whether the user has disabled Location Service functionality for the application.

    // Event handler for the GeoCoordinateWatcher.StatusChanged event.
    void watcher_StatusChanged(object sender, GeoPositionStatusChangedEventArgs e)
    {
        switch (e.Status)
        {
            case GeoPositionStatus.Disabled:
                // The Location Service is disabled or unsupported.
                // Check to see whether the user has disabled the Location Service.
                if (watcher.Permission == GeoPositionPermission.Denied)
                {
                    // The user has disabled the Location Service on their device.
                    statusTextBlock.Text = "you have this application access to location.";
                }
                else
                {
                    statusTextBlock.Text = "location is not functioning on this device";
                }
                break;
    
            case GeoPositionStatus.Initializing:
                // The Location Service is initializing.
                // Disable the Start Location button.
                startLocationButton.IsEnabled = false;
                break;
    
            case GeoPositionStatus.NoData:
                // The Location Service is working, but it cannot get location data.
                // Alert the user and enable the Stop Location button.
                statusTextBlock.Text = "location data is not available.";
                stopLocationButton.IsEnabled = true;
                break;
    
            case GeoPositionStatus.Ready:
                // The Location Service is working and is receiving location data.
                // Show the current position and enable the Stop Location button.
                statusTextBlock.Text = "location data is available.";
                stopLocationButton.IsEnabled = true;
                break;
        }
    }
    
  5. When the Location Service is ready and receiving data, it will begin to raise the PositionChanged event and call your application’s handler if you have implemented one. In the event handler, access the Position member of the GeoPositionChangedEventArgs<(Of <(T>)>) object. The Position field is a GeoPosition object, which consists of a Timestamp and a GeoCoordinate object that contains the location information for the reading. This example accesses the latitude and longitude values.

    void watcher_PositionChanged(object sender, GeoPositionChangedEventArgs<GeoCoordinate> e)
    {
      latitudeTextBlock.Text = e.Position.Location.Latitude.ToString("0.000");
      longitudeTextBlock.Text = e.Position.Location.Longitude.ToString("0.000");
    }
    
  6. Make sure that you stop the Location Service when it is no longer needed, to maximize the battery life of the device. For this example, a Stop Location button is implemented to allow the user to stop the Location Service.

    // Click the event handler for the “Start Location” button.
    private void stopLocationButton_Click(object sender, RoutedEventArgs e)
    {
      watcher.Stop();
    }