MapControl 需要Azure Maps帐户。 按照管理 Azure Maps 帐户的说明创建帐户并获取服务令牌。
这是正确的控制吗?
如果要在应用中显示地理数据,请使用 MapControl,例如:
- 在地图上显示带有标记的位置。
- 显示感兴趣的点集合。
- 通过缩放和平移提供交互式地图体验。
创建 MapControl
- 重要 API: MapControl 类、 MapIcon 类、 MapElementsLayer 类
![]()
WinUI 3 示例库应用包含 WinUI 控件和功能的交互式示例。 从 Microsoft Store 或浏览 GitHub 上的源代码获取应用。
将 MapControl 添加到页面,并将 MapServiceToken 设置为Azure Maps键。
<MapControl x:Name="myMap"
MapServiceToken="YOUR_AZURE_MAPS_TOKEN"
Height="400" />
设置地图位置
设置 Center 和 ZoomLevel 属性以控制地图显示的内容。
using Windows.Devices.Geolocation;
var position = new BasicGeoposition { Latitude = 47.6062, Longitude = -122.3321 };
myMap.Center = new Geopoint(position);
myMap.ZoomLevel = 12;
<!-- Set initial center and zoom in XAML is not supported; set in code-behind -->
<MapControl x:Name="myMap"
MapServiceToken="YOUR_AZURE_MAPS_TOKEN"
Height="400" />
向地图添加图钉
使用 MapIcon 在地图上显示图钉。 将图标添加到 MapElementsLayer,然后将图层添加到地图的 Layers 集合。
using Windows.Devices.Geolocation;
using Microsoft.UI.Xaml.Controls;
using System.Collections.Generic;
var position = new BasicGeoposition
{
Latitude = 47.6062,
Longitude = -122.3321
};
var icon = new MapIcon
{
Location = new Geopoint(position),
};
var layer = new MapElementsLayer
{
MapElements = new List<MapElement> { icon }
};
myMap.Layers.Add(layer);
显示或隐藏交互式控件
InteractiveControlsVisible 属性控制地图是否显示用于缩放、旋转、间距和地图样式的内置覆盖控件。
<MapControl x:Name="myMap"
MapServiceToken="YOUR_AZURE_MAPS_TOKEN"
InteractiveControlsVisible="True"
Height="400" />
处理地图元素单击
订阅 MapElementClick 事件,以在用户单击地图元素(如图钉)时做出响应。
myMap.MapElementClick += (sender, args) =>
{
foreach (var element in args.MapElements)
{
if (element is MapIcon clickedIcon)
{
// Handle the clicked icon
}
}
};
处理地图服务错误
订阅 MapServiceErrorOccurred 事件,以检测与地图服务通信的问题,例如无效或缺少 MapServiceToken。
myMap.MapServiceErrorOccurred += (sender, args) =>
{
// Log or display the error
System.Diagnostics.Debug.WriteLine("Map service error occurred.");
};