共用方式為


地圖控制

MapControl顯示一張象徵性、互動式的地球地圖,由Azure Maps驅動。 你可以顯示位置、新增釘腳和自訂圖層,並讓使用者透過平移、縮放、旋轉和俯仰控制與地圖互動。

MapControl 需要 Azure Maps 帳號。 請依照管理您的Azure Maps帳號的指示建立帳號並取得地圖服務代幣。

這是正確的控制嗎?

當你想在應用程式中顯示地理資料時,可以使用 MapControl,例如:

  • 用圖釘顯示地圖上的位置。
  • 顯示一系列興趣點。
  • 提供互動式地圖體驗,支援縮放與平移。

建立 MapControl

WinUI 3 圖庫圖示 WinUI 3 圖庫應用程式包含互動式的 WinUI 控制項與功能範例。 你可以從 Microsoft Store下載 App,或在 GitHub 瀏覽原始碼。

在你的頁面新增一個 MapControl,並將 MapServiceToken 設為你的 Azure Maps 鍵。

<MapControl x:Name="myMap"
            MapServiceToken="YOUR_AZURE_MAPS_TOKEN"
            Height="400" />

設定地圖位置

設定 CenterZoomLevel 屬性來控制地圖顯示的內容。

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.");
};