コンパスの使用

コンパスを使用して現在の見出しを決定する方法について説明します。

この例では、入力デバイスとしてコンパスに依存する単純なアプリを作成します。 アプリは、磁北または真北に対する現在の方位を取得できます。 ナビゲーション アプリでは、コンパスを使用してデバイスが向いている方向を決定し、それに応じてマップの向きを決定します。

Note

この記事では、コンパスの使用方法を示すコードに焦点を当てます。 コンパス センサーの概要については、「 センサー: コンパス」を参照してください。

前提条件

コンパス センサーとその使用方法を理解している必要があります。 「センサー: コンパス」を参照してください。

使用しているデバイスまたはエミュレーターは、コンパスをサポートしている必要があります。

サンプル コード

using Microsoft.UI.Dispatching;
using Microsoft.UI.Xaml.Controls;
using Windows.Devices.Sensors;

namespace DevicesDemo.Pages
{
    public sealed partial class CompassPage : Page
    {
        private Compass? compass;

        public CompassPage()
        {
            InitializeComponent();

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

            if (compass != null)
            {
                // Establish the report interval for all scenarios.
                uint minReportInterval = compass.MinimumReportInterval;
                uint reportInterval = minReportInterval > 16 ? minReportInterval : 16;
                compass.ReportInterval = reportInterval;

                // Assign an event handler for the reading-changed event.
                compass.ReadingChanged += Compass_ReadingChanged;
            }
            else
            {
                statusBar.Message = "No compass was found.";
                statusBar.Severity = InfoBarSeverity.Error;
                statusBar.IsOpen = true;
            }
        }

        // This event handler writes the current compass
        // reading to the text blocks on the XAML page.
        private void Compass_ReadingChanged(Compass sender, CompassReadingChangedEventArgs args)
        {
            DispatcherQueue?.TryEnqueue(DispatcherQueuePriority.Normal, () =>
            {
                CompassReading reading = args.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.";
            });
        }
    }
}
<Grid>
    <Grid.RowDefinitions>
        <RowDefinition/>
        <RowDefinition Height="Auto"/>
    </Grid.RowDefinitions>
    <Grid Margin="24">
        <Grid.ColumnDefinitions>
            <ColumnDefinition Width="Auto"/>
            <ColumnDefinition/>
        </Grid.ColumnDefinitions>
        <Grid.RowDefinitions>
            <RowDefinition Height="44"/>
            <RowDefinition Height="44"/>
        </Grid.RowDefinitions>
        <TextBlock Text="Magnetic Heading:" Style="{StaticResource LabelTextBlockStyle}"/>
        <TextBlock x:Name="txtMagnetic" Grid.Column="1" Text="---"/>

        <TextBlock Grid.Row="1" Text="True North Heading:" Style="{StaticResource LabelTextBlockStyle}"/>
        <TextBlock x:Name="txtNorth" Grid.Column="1" Grid.Row="1" Text="---"/>
    </Grid>

    <InfoBar x:Name="statusBar" Grid.Row="1"/>
</Grid>

アプリの実行時に、デバイスを移動することでコンパスの値を変更できます。

前の例は、コンパス入力をアプリに統合するために記述する必要がある重要なコードを示しています。

センサーに接続する

GetDefault メソッドを呼び出して、既定のコンパスとの接続を確立します。

private Compass? compass;
// ...
compass = Compass.GetDefault();

FromIdAsync を呼び出して、DeviceInformation.Id 値から Compass オブジェクトを作成することもできます。 詳細については、「デバイスの 列挙」を参照してください。

コンパス センサーが検出されない場合は、ステータス メッセージが更新され、ユーザーに通知されます。

レポート間隔を設定する

レポート間隔は、ページのコンストラクター内で設定されます。 このコードは、デバイスでサポートされている最小間隔を取得し、16 ミリ秒 (約 60 Hz のリフレッシュ レート) の要求された間隔と比較します。 サポートされる最小間隔が要求された間隔より大きい場合、コードは値を最小値に設定します。 それ以外の場合は、要求された間隔に値が設定されます。

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

センサー データの読み取り

新しいコンパス データは 、ReadingChanged イベント ハンドラーでキャプチャされます。 センサー ドライバーは、センサーから新しいデータを受信するたびに、このイベントを使用して値をアプリに渡します。 この例では、これらの新しい値は、対応するページの XAML で見つかったテキスト ブロックに書き込まれます。

compass.ReadingChanged += Compass_ReadingChanged;
// ...

private void Compass_ReadingChanged(Compass sender, CompassReadingChangedEventArgs args)
{
    DispatcherQueue?.TryEnqueue(DispatcherQueuePriority.Normal, () =>
    {
        CompassReading reading = args.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.";
    });
}