Windows 应用 SDK和 WinUI 3 提供用于显示地图、检测用户位置以及设置地理围栏的 API 和控件。 使用这些功能生成应用,这些应用显示带有图钉的交互式地图、跟踪用户的位置,以及当用户进入或离开地理区域时触发操作。
本文介绍了各项功能,并包含一个完整示例,该示例将MapControl、Geolocator和GeofenceMonitor结合到一个可运行的应用中。
使用 MapControl 显示地图
MapControl 显示由Azure Maps提供支持的交互式地图。 可以添加图钉、图层,并响应用户的交互操作,例如平移、缩放和单击等操作。
MapControl 需要Azure Maps帐户。 请参阅“管理Azure Maps帐户”以创建帐户并获取服务令牌。
有关详细的使用说明,请参阅 MapControl。
<MapControl x:Name="myMap"
MapServiceToken="YOUR_AZURE_MAPS_TOKEN"
Height="400" />
注释
UWP MapControl 和Windows。Services.Maps API 已弃用,在将来的 Windows 版本中可能不可用。 WinUI 3 应用应使用上述新 MapControl。 有关详细信息,请参阅 已弃用功能的资源。
检测用户的位置
Windows。Devices.Geolocation API 允许你获取设备的地理位置。 这些 API 适用于 UWP 和 Windows 应用 SDK (WinUI 3) 应用。 您可以:
- 使用 Geolocator.GetGeopositionAsync获取一次性位置。
- 使用 Geolocator.PositionChanged 事件跟踪随时间变化的位置变化。
- 使用 GeovisitMonitor监测到访状态变化,以实现低电量消耗的位置感知。
有关分步指南,请参阅 “获取用户的位置”。
设置地理围栏
地理围栏定义地理边界。 当用户进入或退出边界时,应用会收到通知。 地理围栏适用于基于位置的提醒、警报或内容分发。
有关创建和监视地理围栏的说明,请参阅 设置地理围栏。
位置功能和隐私
所有位置 API 都需要在应用的程序包清单中声明 的位置 功能。 在访问位置数据之前,还必须在运行时调用 Geolocator.RequestAccessAsync 。
Windows允许用户控制哪些应用可以通过“设置隐私和安全>位置”>访问其位置。 你的应用应处理用户拒绝或撤销位置访问的情况。
完整示例
以下示例将 MapControl、Geolocator 和 GeofenceMonitor 整合到同一个 WinUI 3 窗口中。 如果未配置 Azure Maps 密钥,地图会正常降级,而地理定位和地理围栏继续工作。
先决条件
- Windows 应用 SDK 2.2 或更高版本
- Azure Maps 密钥——显示地图切片所必需。 如果没有有效的密钥,MapControl 仍会被渲染出来,但地图将显示为空白。
- 在
Package.appxmanifest中声明的位置设备功能:
<DeviceCapability Name="location" />
在运行应用之前,请将Azure Maps密钥设置为环境变量:
$env:AZURE_MAPS_KEY = "your-key-here"
MainWindow.xaml
左侧是一个 300 像素宽的控制面板,带有按钮和状态文本,右侧是一个 MapControl。 缺少 Azure Maps 密钥时,会显示叠加层。
<?xml version="1.0" encoding="utf-8" ?>
<Window
x:Class="MapLocationDemo.MainWindow"
xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
Title="Map Location Demo">
<Window.SystemBackdrop>
<MicaBackdrop />
</Window.SystemBackdrop>
<Grid>
<Grid.RowDefinitions>
<RowDefinition Height="Auto" />
<RowDefinition Height="*" />
</Grid.RowDefinitions>
<TitleBar Title="Map Location Demo" />
<Grid Grid.Row="1">
<Grid.ColumnDefinitions>
<ColumnDefinition Width="300" />
<ColumnDefinition Width="*" />
</Grid.ColumnDefinitions>
<Grid Grid.Column="0" Margin="16" RowSpacing="12">
<Grid.RowDefinitions>
<RowDefinition Height="Auto"/>
<RowDefinition Height="Auto"/>
<RowDefinition Height="Auto"/>
<RowDefinition Height="*"/>
</Grid.RowDefinitions>
<TextBlock Text="Location Demo" FontSize="20" FontWeight="Bold"/>
<StackPanel Grid.Row="1" Spacing="8">
<Button x:Name="FindMeButton" Content="Find My Location"
Click="FindMeButton_Click" HorizontalAlignment="Stretch"/>
<Button x:Name="AddGeofenceButton" Content="Add Geofence Here"
Click="AddGeofenceButton_Click" HorizontalAlignment="Stretch"/>
</StackPanel>
<TextBlock x:Name="StatusText" Grid.Row="2"
Text="Click 'Find My Location' to begin." TextWrapping="Wrap"/>
<ListView x:Name="EventLog" Grid.Row="3" Header="Event Log"/>
</Grid>
<Grid Grid.Column="1">
<MapControl x:Name="MyMap" />
<StackPanel x:Name="MapKeyMissing" Visibility="Collapsed"
HorizontalAlignment="Center" VerticalAlignment="Center"
Spacing="8">
<FontIcon Glyph="" FontSize="48"
HorizontalAlignment="Center"
Foreground="{ThemeResource SystemFillColorCautionBrush}" />
<TextBlock Text="Azure Maps key not configured"
FontSize="18" FontWeight="SemiBold"
HorizontalAlignment="Center" />
<TextBlock x:Name="MapKeyHint" TextWrapping="Wrap" MaxWidth="400"
HorizontalAlignment="Center" TextAlignment="Center"
Foreground="{ThemeResource TextFillColorSecondaryBrush}" />
</StackPanel>
</Grid>
</Grid>
</Grid>
</Window>
MainWindow.xaml.cs
using System;
using System.Collections.Generic;
using Microsoft.UI.Xaml;
using Microsoft.UI.Xaml.Controls;
using Windows.Devices.Geolocation;
using Windows.Devices.Geolocation.Geofencing;
namespace MapLocationDemo;
public sealed partial class MainWindow : Window
{
private Geolocator? _geolocator;
private BasicGeoposition _lastPosition;
private bool _mapAvailable;
public MainWindow()
{
InitializeComponent();
_mapAvailable = TryConfigureMap();
GeofenceMonitor.Current.GeofenceStateChanged += OnGeofenceStateChanged;
}
// Read the Azure Maps key from an environment variable.
// If missing, collapse the map and show an informational overlay.
private bool TryConfigureMap()
{
var key = Environment.GetEnvironmentVariable("AZURE_MAPS_KEY");
if (string.IsNullOrWhiteSpace(key))
{
MyMap.Visibility = Visibility.Collapsed;
MapKeyMissing.Visibility = Visibility.Visible;
MapKeyHint.Text = "Set the AZURE_MAPS_KEY environment variable "
+ "and restart.\nGeolocation and geofencing still work "
+ "without the map.";
Log("Azure Maps key not found — map disabled");
return false;
}
MyMap.MapServiceToken = key;
return true;
}
private async void FindMeButton_Click(object sender, RoutedEventArgs e)
{
FindMeButton.IsEnabled = false;
StatusText.Text = "Requesting location access...";
var access = await Geolocator.RequestAccessAsync();
if (access != GeolocationAccessStatus.Allowed)
{
StatusText.Text =
"Location access denied. Check Settings > Privacy > Location.";
FindMeButton.IsEnabled = true;
return;
}
_geolocator = new Geolocator { DesiredAccuracyInMeters = 100 };
try
{
var pos = await _geolocator.GetGeopositionAsync();
var lat = pos.Coordinate.Point.Position.Latitude;
var lon = pos.Coordinate.Point.Position.Longitude;
_lastPosition = new BasicGeoposition
{
Latitude = lat, Longitude = lon
};
StatusText.Text =
$"Location: {lat:F5}, {lon:F5} ({pos.Coordinate.Accuracy:F0} m)";
Log($"Position: {lat:F5}, {lon:F5}");
if (_mapAvailable)
{
var pt = new Geopoint(_lastPosition);
MyMap.Center = pt;
MyMap.ZoomLevel = 15;
var layer = new MapElementsLayer();
layer.MapElements = new List<MapElement>
{
new MapIcon { Location = pt }
};
MyMap.Layers.Clear();
MyMap.Layers.Add(layer);
}
}
catch (Exception ex) { StatusText.Text = $"Error: {ex.Message}"; }
finally { FindMeButton.IsEnabled = true; }
}
private void AddGeofenceButton_Click(object sender, RoutedEventArgs e)
{
if (_lastPosition.Latitude == 0 && _lastPosition.Longitude == 0)
{
StatusText.Text = "Get your location first.";
return;
}
var fence = new Geofence("MyGeofence",
new Geocircle(_lastPosition, 200),
MonitoredGeofenceStates.Entered | MonitoredGeofenceStates.Exited,
false, TimeSpan.FromSeconds(5));
GeofenceMonitor.Current.Geofences.Add(fence);
StatusText.Text = $"Geofence added at "
+ $"{_lastPosition.Latitude:F5}, {_lastPosition.Longitude:F5}";
Log("Geofence registered");
}
private void OnGeofenceStateChanged(
GeofenceMonitor sender, object args)
{
var reports = sender.ReadReports();
DispatcherQueue.TryEnqueue(() =>
{
foreach (var r in reports)
{
var msg = r.NewState switch
{
GeofenceState.Entered => $"Entered: {r.Geofence.Id}",
GeofenceState.Exited => $"Exited: {r.Geofence.Id}",
GeofenceState.Removed => $"Removed: {r.Geofence.Id}",
_ => null
};
if (msg != null) { StatusText.Text = msg; Log(msg); }
}
});
}
private void Log(string msg) =>
EventLog.Items.Insert(0, $"[{DateTime.Now:HH:mm:ss}] {msg}");
}
主要模式
-
MapControl内置于 Windows 应用 SDK 1.6 及更高版本中。 将MapServiceToken设置为你的 Azure Maps 密钥。 -
TryConfigureMap在AZURE_MAPS_KEY启动时检查环境变量。 如果变量为空,地图会折叠起来,并显示一个覆盖层来说明如何解决这个问题——不会崩溃,也不会出现空白地图。 -
Package.appxmanifest中的DeviceCapability Name="location"是必需的,否则Geolocator.RequestAccessAsync会返回Denied。 -
GeofenceMonitor.GeofenceStateChanged在后台线程上触发,因此请使用DispatcherQueue.TryEnqueue更新 UI。