Location of Windows 8 Metro

Source: Internet
Author: User
Document directory
  • 1. Overview
  • 2. Guidelines
  • 3. C # example
1. Overview
  • There are four Geographic Positioning Methods: WiFi, IP address, mobile phone base station, and GPS.

  • Win8 has built-in WiFi, IP address two methods, WiFi positioning accuracy is about 350 meters, IP address precision is 25 km.

  • The Win8 positioning service does not provide orientation, height, speed, address, and other data.

  • When you need to use the location service, you need to explicitly remind the user and enable the location service in the privacy settings of window8.

  • Enable the location service in the application capability.
2. Guidelines
  • Only one request for positioning is called.Getgeopostionasync() Method.

  • Set the trajectory data change threshold by settingMovementthresholdAttribute, triggered only when the value changes beyond the range of this valuePositionchangedEvents, such as weather changes between cities.

  • Set the location data report frequency by settingReportintervalProperty. If the value is 0, it changes in real time. Note: Some devices may be useless to set this attribute.

  • Set the precision by settingDesiredaccuracyProperty. GPS is called only when the precision is high.

  • Startup delay, which may take 2 seconds. Do not block the UI.

  • Run in the background. When an application is suspended, data will not be updated. Therefore, consider running in the background.

  • CaptureStatuschangedEvent to understand the available status of the location service.
  • When the location service is disabledGetgeopostionasync() An exception will be reported,LocationstatusIf the value is disable, you must be reminded to enable the location service.
  • Cache data should be cleared when the status is unavailable.
  • When you enable the location function again, no event is generated. You can only obtain the event by requesting data from the program.
  • When an application is suspended to activated, it must obtain location data again.
  • A refresh button is provided to allow users to obtain location data again.
  • We recommend that you prompt "your location is currently turned off. Change your settings through the settings charm to turn it back on ."
  • If the location is not important information, use the notification. If the location is important information, such as a map, use flyout.
3. C # example

Obtain location data

using System;using System.Collection.Generic;using System.Linq;using System.Threading.Tasks;using Windows.Foundation;using Windows.UI.DirectUI;using Windows.UI.DirectUI.Controls;using Windows.UI.DirectUI.Data;using Windows.Devices.Geolocation;namespace GeolocationSample{    partial class MainPage    {        Geolocator geo = null;        public MainPage()        {            InitializeComponent();        }                private async void button1_Click(            object sender, RoutedEventArgs e)        {            if (geo == null)            {                geo = new Geolocator();            }                        IGeoposition pos = await geo.GetGeopositionAsync();                        textblockLatitude.Text = "Latitude: " + pos.Coordinate.Latitude.ToString();            textblockLongitude.Text = "Longitude: " + pos.Coordinate.Longitude.ToString();            textblockAccuracy.Text = "Accuracy: " + pos.Coordinate.Accuracy.ToString();        }    }}

 

Obtain location change data

using System;using System.Collection.Generic;using System.Linq;using System.Threading.Tasks;using Windows.Foundation;using Windows.UI.Core;using Windows.UI.DirectUI;using Windows.UI.DirectUI.Controls;using Windows.UI.DirectUI.Data;using Windows.Devices.Geolocation; namespace GeolocationEventsSample{    partial class MainPage    {        private Geolocator geo = null;        private CoreDispatcher _cd;         public MainPage()        {            InitializeComponent();            _cd = Window.Current.CoreWindow.Dispatcher;        }                private void button1_Click(object sender, RoutedEventArgs e)        {            if (geo == null)            {                geo = new Geolocator();            }            if (geo != null)            {                geo.PositionChanged +=                     new TypedEventHandler<Geolocator,                        PositionChangedEventArgs>(geo_PositionChanged);            }        }             private void button2_Click(object sender, RoutedEventArgs e)     {         if (geo != null)         {             geo.PositionChanged -= new TypedEventHandler<Geolocator, PositionChangedEventArgs> (geo_PositionChanged);         }     }            private void geo_PositionChanged(Geolocator sender, PositionChangedEventArgs e)     {         _cd.InvokeAsync(CoreDispatcherPriority.Normal, (s, a) =>         {             IGeoposition pos = (a.Context as IPositionChangedEventArgs).Position;             textLatitude.Text = "Latitude: " + pos.Coordinate.Latitude.ToString();             textLongitude.Text = "Longitude: " + pos.Coordinate.Longitude.ToString();             textAccuracy.Text = "Accuracy: " + pos.Coordinate.Accuracy.ToString();          }, this, e);     }   }}

 

Set the location data change threshold

using System;using System.Collections.Generic;using System.IO;using System.Linq;using Windows.Foundation;using Windows.Foundation.Collections;using Windows.UI.Xaml;using Windows.UI.Xaml.Controls;using Windows.UI.Xaml.Controls.Primitives;using Windows.UI.Xaml.Data;using Windows.UI.Xaml.Input;using Windows.UI.Xaml.Media;using Windows.UI.Xaml.Navigation;using Windows.UI.Core;using Windows.Devices.Geolocation;// The Blank Page item template is documented at http://go.microsoft.com/fwlink/?LinkId=234238namespace GeolocationAdjustDistance{    /// <summary>    /// An empty page that can be used on its own or navigated to within a Frame.    /// </summary>    public sealed partial class BlankPage : Page    {        private Geolocator geo = null;        private CoreDispatcher _cd;        private double prevLatitude = -1;        private double prevLongitude = -1;        private double totalDistance = 0;        public BlankPage()        {            this.InitializeComponent();            _cd = Window.Current.CoreWindow.Dispatcher;        }        /// <summary>        /// Invoked when this page is about to be displayed in a Frame.        /// </summary>        /// <param name="e">Event data that describes how this page was reached.  The Parameter        /// property is typically used to configure the page.</param>        protected override void OnNavigatedTo(NavigationEventArgs e)        {        }        private void Button_Click_1(object sender, RoutedEventArgs e)        {            if (geo == null)            {                geo = new Geolocator();            }            if (geo != null)            {                geo.PositionChanged += new TypedEventHandler<Geolocator,                    PositionChangedEventArgs>(geo_PositionChanged);                geo.StatusChanged += new TypedEventHandler<Geolocator,                    StatusChangedEventArgs>(geo_StatusChanged);                geo.MovementThreshold = float.Parse(tbThreshold.Text);                tbThreshold.IsEnabled = false;                TextBox1.Text = "Tracking Started " +                                 "(Time, Latitude, Longitude, Distance)\n";            }        }        private void Button_Click_2(object sender, RoutedEventArgs e)        {            if (geo != null)            {                geo.PositionChanged -= new TypedEventHandler<Geolocator,                    PositionChangedEventArgs>(geo_PositionChanged);                geo.StatusChanged -= new TypedEventHandler<Geolocator,                     StatusChangedEventArgs>(geo_StatusChanged);                TextBox1.Text += "\nTracking Stopped.\n" +                                 "Total Distance recorded: " +                                 totalDistance.ToString("F2") + " m\n";                tbThreshold.IsEnabled = true;            }        }        private double CalculateDistance(double prevLat, double prevLong, double currLat, double currLong)        {            const double degreesToRadians = (Math.PI / 180.0);            const double earthRadius = 6371; // kilometers            // convert latitude and longitude values to radians            var prevRadLat = prevLat * degreesToRadians;            var prevRadLong = prevLong * degreesToRadians;            var currRadLat = currLat * degreesToRadians;            var currRadLong = currLong * degreesToRadians;            // calculate radian delta between each position.            var radDeltaLat = currRadLat - prevRadLat;            var radDeltaLong = currRadLong - prevRadLong;            // calculate distance            var expr1 = (Math.Sin(radDeltaLat / 2.0) *                         Math.Sin(radDeltaLat / 2.0)) +                        (Math.Cos(prevRadLat) *                          Math.Cos(currRadLat) *                         Math.Sin(radDeltaLong / 2.0) *                          Math.Sin(radDeltaLong / 2.0));            var expr2 = 2.0 * Math.Atan2(Math.Sqrt(expr1),                                          Math.Sqrt(1 - expr1));            var distance = (earthRadius * expr2);             return distance * 1000;  // return results as meters        }        void geo_PositionChanged(Geolocator sender, PositionChangedEventArgs args)        {            _cd.InvokeAsync(CoreDispatcherPriority.Normal, (s, a) =>            {                Geoposition pos = (a.Context as IPositionChangedEventArgs).Position;                double updateDistance = 0;                // Calculate distance;                if ( ( prevLatitude == -1 ) || ( prevLongitude == -1 ) )                 {                   updateDistance = 0;                } else {                   updateDistance = CalculateDistance( prevLatitude, prevLongitude,                       pos.Coordinate.Latitude, pos.Coordinate.Longitude );                }               // Update tracking               prevLatitude = pos.Coordinate.Latitude;               prevLongitude = pos.Coordinate.Longitude;               totalDistance += updateDistance;               // display the results.               TextBox1.Text += "Position Update: " +                                pos.Coordinate.Timestamp.ToString("T") + ", " +                                pos.Coordinate.Latitude.ToString("F3") + ", " +                                pos.Coordinate.Longitude.ToString("F3") + ", " +                                updateDistance.ToString("F2") + " m\n";            }, this, args);        }        void geo_StatusChanged(Geolocator sender, StatusChangedEventArgs args)        {            var newStatus = args.Status;            var strStatus = "";            switch (newStatus)            {                case PositionStatus.Ready:                     strStatus = "Location is available.";                    break;                case PositionStatus.Initializing:                    strStatus = "Geolocation service is initializing.";                    break;                case PositionStatus.NoData:                    strStatus = "Location service data is not available.";                    break;                case PositionStatus.Disabled:                    strStatus = "Location services are disabled. Use the " +                                "Settings charm to enable them.";                    break;                case PositionStatus.NotInitialized:                    strStatus = "Location status is not initialized because " +                                "the app has not yet requested location data.";                    break;                case PositionStatus.NotAvailable:                    strStatus = "Location services are not supported on your system.";                    break;                default:                    strStatus = "Unknown PositionStatus value (" +                                 newStatus.ToString() + ").";                    break;            }            _cd.InvokeAsync(CoreDispatcherPriority.Normal, (s, a) =>            {               TextBox1.Text += strStatus + "\n";            }, this, args);        }    }}

 

 

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.