使用指南针

了解如何使用指南针确定当前航向。

重要的应用程序接口(API)

先决条件

应熟悉可扩展应用程序标记语言(XAML)、Microsoft Visual C# 和事件。

你正在使用的设备或模拟器必须支持指南针。

创建简单的指南针应用

应用可以检索相对于磁北或正北的当前方位。 导航应用使用指南针确定设备面向的方向,然后相应地定位地图。

注释

有关更完整的实现,请参阅 指南针示例

说明书

  • 创建一个新项目,从 Visual C# 项目模板中选择 空白应用程序(通用 Windows)

  • 打开项目的MainPage.xaml.cs文件,并将现有代码替换为以下内容。

    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; // Required to access the core dispatcher object
    using Windows.Devices.Sensors; // Required to access the sensor platform and the compass


    namespace App1
    {
        /// <summary>
        /// An empty page that can be used on its own or navigated to within a Frame.
        /// </summary>
        public sealed partial class MainPage : Page
        {
            private Compass _compass; // Our app' s compass object

            // This event handler writes the current compass reading to
            // the textblocks on the app' s main page.

            private async void ReadingChanged(object sender, CompassReadingChangedEventArgs e)
            {
               await Dispatcher.RunAsync(CoreDispatcherPriority.Normal, () =>
                {
                    CompassReading reading = e.Reading;
                    txtMagnetic.Text = String.Format("{0,5:0.00}", reading.HeadingMagneticNorth);
                    if (reading.HeadingTrueNorth.HasValue)
                        txtNorth.Text = String.Format("{0,5:0.00}", reading.HeadingTrueNorth);
                    else
                        txtNorth.Text = "No reading.";
                });
            }

            public MainPage()
            {
                this.InitializeComponent();
               _compass = Compass.GetDefault(); // Get the default compass object

                // Assign an event handler for the compass reading-changed event
                if (_compass != null)
                {
                    // Establish the report interval for all scenarios
                    uint minReportInterval = _compass.MinimumReportInterval;
                    uint reportInterval = minReportInterval > 16 ? minReportInterval : 16;
                    _compass.ReportInterval = reportInterval;
                    _compass.ReadingChanged += new TypedEventHandler<Compass, CompassReadingChangedEventArgs>(ReadingChanged);
                }
            }
        }
    }

需要用你为项目指定的名称重命名前一个代码片段中的命名空间。 例如,如果创建了名为 CompassCS的项目,则需要将 namespace App1 替换为 namespace CompassCS

  • 打开文件 MainPage.xaml,并将原始内容替换为以下 XML。
    <Page
        x:Class="App1.MainPage"
        xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
        xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
        xmlns:local="using:App1"
        xmlns:d="http://schemas.microsoft.com/expression/blend/2008"
        xmlns:mc="http://schemas.openxmlformats.org/markup-compatibility/2006"
        mc:Ignorable="d">

        <Grid x:Name="LayoutRoot" Background="#FF0C0C0C">
            <TextBlock HorizontalAlignment="Left" Height="22" Margin="8,18,0,0" TextWrapping="Wrap" Text="Magnetic Heading:" VerticalAlignment="Top" Width="104" Foreground="#FFFBF9F9"/>
            <TextBlock HorizontalAlignment="Left" Height="18" Margin="8,58,0,0" TextWrapping="Wrap" Text="True North Heading:" VerticalAlignment="Top" Width="104" Foreground="#FFF3F3F3"/>
            <TextBlock x:Name="txtMagnetic" HorizontalAlignment="Left" Height="22" Margin="130,18,0,0" TextWrapping="Wrap" Text="TextBlock" VerticalAlignment="Top" Width="116" Foreground="#FFFBF6F6"/>
            <TextBlock x:Name="txtNorth" HorizontalAlignment="Left" Height="18" Margin="130,58,0,0" TextWrapping="Wrap" Text="TextBlock" VerticalAlignment="Top" Width="116" Foreground="#FFF5F1F1"/>

         </Grid>
    </Page>

需要将上一代码段中类名的第一部分替换为应用的命名空间。 例如,如果创建了名为 CompassCS的项目,则需要将 x:Class="App1.MainPage" 替换为 x:Class="CompassCS.MainPage"。 还应将 xmlns:local="using:App1" 替换为 xmlns:local="using:CompassCS"

  • 按 F5 或选择 调试>启动调试 生成、部署和运行应用。

应用运行后,可以通过移动设备或使用仿真器工具来更改指南针值。

  • 返回到 Visual Studio,按 Shift+F5 或选择“调试”“停止调试”> 来结束应用程序。

说明

前面的示例演示了在应用中集成指南针输入所需的代码很少。

应用在 MainPage 方法中与默认指南针建立连接。

_compass = Compass.GetDefault(); // Get the default compass object

应用程序在 MainPage 方法中建立报告间隔。 此代码检索设备支持的最小间隔,并将其与请求的间隔 16 毫秒(大约为 60-Hz 刷新率)进行比较。 如果支持的最小间隔大于请求的间隔,则代码会将该值设置为最小值。 否则,它会将值设置为请求的间隔。

uint minReportInterval = _compass.MinimumReportInterval;
uint reportInterval = minReportInterval > 16 ? minReportInterval : 16;
_compass.ReportInterval = reportInterval;

新的指南针数据在 ReadingChanged 方法中被捕获到。 传感器驱动程序每次从传感器接收新数据时,都会使用此事件处理程序将值传递给应用。 应用在以下行中注册此事件处理程序。

_compass.ReadingChanged += new TypedEventHandler<Compass,
CompassReadingChangedEventArgs>(ReadingChanged);

这些新值将写入项目 XAML 中的 TextBlock 标签。

 <TextBlock HorizontalAlignment="Left" Height="22" Margin="8,18,0,0" TextWrapping="Wrap" Text="Magnetic Heading:" VerticalAlignment="Top" Width="104" Foreground="#FFFBF9F9"/>
 <TextBlock HorizontalAlignment="Left" Height="18" Margin="8,58,0,0" TextWrapping="Wrap" Text="True North Heading:" VerticalAlignment="Top" Width="104" Foreground="#FFF3F3F3"/>
 <TextBlock x:Name="txtMagnetic" HorizontalAlignment="Left" Height="22" Margin="130,18,0,0" TextWrapping="Wrap" Text="TextBlock" VerticalAlignment="Top" Width="116" Foreground="#FFFBF6F6"/>
 <TextBlock x:Name="txtNorth" HorizontalAlignment="Left" Height="18" Margin="130,58,0,0" TextWrapping="Wrap" Text="TextBlock" VerticalAlignment="Top" Width="116" Foreground="#FFF5F1F1"/>