使用 Azure 地圖服務的地圖控制項

Azure 地圖服務 Web SDK 提供地圖控制項,可讓您使用自己的內容和影像來自訂互動式地圖,以便在您的 Web 或行動應用程式中顯示。 此模組是協助程式程式庫,透過使用 JavaScript 或 TypeScript,可讓您輕鬆地在 Web 或 Node.js 應用程式中使用 Azure 地圖服務 REST 服務。

本文使用 Azure 地圖服務 Web SDK,不過 Azure 地圖服務會使用任何地圖控制項。 如需第三方地圖控制項外掛程式的清單,請參閱 Azure 地圖服務社群 - 開放原始碼專案

注意

Azure 地圖服務 Web SDK 地圖控制項 v1 淘汰

第 1 版的 Web SDK 地圖控制項現已被取代,將於 9/19/26 淘汰。 若要避免服務中斷,請在 9/19/26 前移轉至第 3 版的 Web SDK 地圖控制項。 第 3 版可回溯相容並具有數個優點,包括 WebGL 2 相容性、提高 3D 地形底圖的效能和支援。 如需詳細資訊,請參閱 Azure 地圖服務 Web SDK v1 移轉指南

必要條件

若要在網頁中使用地圖控制項,您必須具備下列其中一個必要條件:

在網頁中建立新的地圖

您可以使用地圖控制項用戶端 JavaScript 程式庫,在網頁中內嵌地圖。

  1. 建立新的 HTML 檔案。

  2. 載入 Azure 地圖服務 Web SDK。 您有兩個選項可選擇:

    • 在 HTML 檔案的 stylesheet 元素中新增 JavaScript 和 <head> 的參考,以使用 Azure 地圖服務 Web SDK 的全域裝載 CDN 版本。:

      <link rel="stylesheet" href="https://atlas.microsoft.com/sdk/javascript/mapcontrol/3/atlas.min.css" type="text/css">
      <script src="https://atlas.microsoft.com/sdk/javascript/mapcontrol/3/atlas.min.js"></script>
      
    • 使用 azure-maps-control npm 套件於本機載入 Azure 地圖服務 Web SDK,並搭配您的應用程式裝載它。 此套件也包含 TypeScript 定義。

      npm install azure-maps-control

    然後將 Azure 地圖服務 stylesheet 的參考新增至檔案的 <head> 元素:

    <link rel="stylesheet" href="https://atlas.microsoft.com/sdk/javascript/mapcontrol/3/atlas.min.css" type="text/css" />
    

    注意

    您可以藉由新增下列程式碼,將 TypeScript 定義匯入您的應用程式:

    import * as atlas from 'azure-maps-control';
    
  3. 若要轉譯地圖來使它填滿頁面的完整主體,請將下列 <style> 元素新增到 <head> 元素。

     <style>
         html, body {
             margin: 0;
         }
    
         #myMap {
             height: 100vh;
             width: 100vw;
         }
     </style>
    
  4. 在頁面的主體中,新增 <div> 元素,並為它提供 myMapid

     <body onload="InitMap()">
         <div id="myMap"></div>
     </body>
    
  5. 現在,初始化地圖控制項。 若要驗證控制項,請使用 Azure 地圖服務訂用帳戶金鑰或 Microsoft Entra 認證搭配驗證選項

    如果您使用訂用帳戶金鑰進行驗證,請將下列指令碼元素複製並貼到 <head> 元素內,以及第一個 <script> 元素下方。 以您的 Azure 地圖服務訂用帳戶金鑰替換 <Your Azure Maps Key>

    <script type="text/javascript">
        function InitMap()
        {
            var map = new atlas.Map('myMap', {
                center: [-122.33, 47.6],
                zoom: 12,
                language: 'en-US',
                authOptions: {
                    authType: 'subscriptionKey',
                    subscriptionKey: '<Your Azure Maps Key>'
                }
            });
       }
    </script>
    

    如果您使用 Microsoft Entra ID 進行驗證,請將下列指令碼元素複製並貼到 <head> 元素內,以及第一個 <script> 元素下方。

    <script type="text/javascript">
      function InitMap()
      {
          var map = new atlas.Map('myMap', {
              center: [-122.33, 47.6],
              zoom: 12,
              language: 'en-US',
              authOptions: {
                  authType: 'aad',
                  clientId: '<Your Microsoft Entra Client Id>',
                  aadAppId: '<Your Microsoft Entra App Id>',
                  aadTenant: '<Your Microsoft Entra tenant Id>'
              }
          });
      }
    </script>
    

    如需有關 Azure 地圖服務驗證的詳細資訊,請參閱 Azure 地圖服務驗證的文件。 如需示範如何將 Azure AD 與 Azure 地圖服務整合的範例清單,請參閱 GitHub 中的 Azure 地圖服務和 Azure Active Directory 範例

    提示

    在此範例中,我們已傳入 <div> 地圖的 id。 這麼做的另一種方式是藉由傳遞 document.getElementById('myMap') 作為第一個參數來傳入 HTMLElement 物件。

  6. 或者,您可能會發現將下列 meta 元素新增至 head 頁面的元素會很有幫助:

     <!-- Ensures that IE and Edge uses the latest version and doesn't emulate an older version -->
     <meta http-equiv="x-ua-compatible" content="IE=Edge">
    
     <!-- Ensures the web page looks good on all screen sizes. -->
     <meta name="viewport" content="width=device-width, initial-scale=1, shrink-to-fit=no">
    
  7. 您的 HTML 檔案現在看起來應該類似以下程式碼片段:

     <!DOCTYPE html>
     <html>
     <head>
         <title></title>
    
         <meta charset="utf-8">
    
         <!-- Ensures that IE and Edge uses the latest version and doesn't emulate an older version -->
         <meta http-equiv="x-ua-compatible" content="IE=Edge">
    
         <!-- Ensures the web page looks good on all screen sizes. -->
         <meta name="viewport" content="width=device-width, initial-scale=1, shrink-to-fit=no">
    
         <!-- Add references to the Azure Maps Map control JavaScript and CSS files. -->
         <link rel="stylesheet" href="https://atlas.microsoft.com/sdk/javascript/mapcontrol/3/atlas.min.css" type="text/css">
         <script src="https://atlas.microsoft.com/sdk/javascript/mapcontrol/3/atlas.min.js"></script>
    
    
         <script type="text/javascript">
             //Create an instance of the map control and set some options.
             function InitMap()
             {
                 var map = new atlas.Map('myMap', {
                     center: [-122.33, 47.6],
                     zoom: 12,
                     language: 'en-US',
                     authOptions: {
                         authType: 'subscriptionKey',
                         subscriptionKey: '<Your Azure Maps Key>'
                     }
                 });
             }
         </script>
    
         <style>
             html, body {
                 margin: 0;
             }
    
             #myMap {
                 height: 100vh;
                 width: 100vw;
             }
         </style>
     </head>
     <body onload="InitMap()">
         <div id="myMap"></div>
     </body>
     </html>
    
  8. 在網頁瀏覽器中開啟此檔案,並檢視轉譯的地圖。 看起來應該如下圖所示:

    Screenshot of a map image showing rendered result.

將地圖當地語系化

Azure 地圖服務提供兩種不同的方式供您設定已轉譯地圖的語言和區域檢視。 第一個選項是將這項資訊新增至全球 atlas 命名空間,這會導致應用程式中的所有地圖控制項執行個體預設為這些設定。 以下範例會將語言設定為法文 ("fr-FR"),並將區域檢視設為「自動」:

atlas.setLanguage('fr-FR');
atlas.setView('Auto');

第二個選項是在載入地圖時,將此資訊傳入地圖選項中,如下所示:

map = new atlas.Map('myMap', {
    language: 'fr-FR',
    view: 'Auto',

    authOptions: {
        authType: 'aad',
        clientId: '<Your AAD Client Id>',
        aadAppId: '<Your AAD App Id>',
        aadTenant: '<Your AAD Tenant Id>'
    }
});

注意

您可以在相同頁面上使用不同語言和區域設定載入多個地圖執行個體。 此外,您可以使用地圖的 setStyle 函式,在地圖載入之後更新這些設定。

以下範例會示範語言設為 "fr-FR" 且區域檢視設為 Auto 的 Azure 地圖服務。

Screenshot showing a map image with its labels in French.

如需支援的語言和區域檢視清單,請參閱 Azure 地圖服務中的當地語系化支援

WebGL 2 相容性

從 Azure 地圖服務 Web SDK 3.0 開始,Web SDK 包含與 WebGL 2 的完整相容性,這是一種強大的圖形技術,可在新式網頁瀏覽器中啟用硬體加速轉譯。 開發人員可使用 WebGL 2,運用新式 GPU 的功能,更有效率地轉譯複雜的地圖和視覺效果,進而提升效能和視覺品質。

Map image showing WebGL 2 Compatibility.

<!DOCTYPE html>
<html lang="en">
    <head>
        <meta charset="utf-8" />
        <meta name="viewport" content="width=device-width, user-scalable=no" />
        <title>WebGL2 - Azure Maps Web SDK Samples</title>
        <link href=https://atlas.microsoft.com/sdk/javascript/mapcontrol/3/atlas.min.css rel="stylesheet"/>
        <script src=https://atlas.microsoft.com/sdk/javascript/mapcontrol/3/atlas.min.js></script>
        <script src="https://unpkg.com/deck.gl@latest/dist.min.js"></script>
        <style>
            html,
            body {
                width: 100%;
                height: 100%;
                padding: 0;
                margin: 0;
            }
            #map {
                width: 100%;
                height: 100%;
            }
        </style>
    </head>
    <body>
        <div id="map"></div>
        <script>
            var map = new atlas.Map("map", {
                center: [-122.44, 37.75],
                bearing: 36,
                pitch: 45,
                zoom: 12,
                style: "grayscale_light",
                // Get an Azure Maps key at https://azuremaps.com/.
                authOptions: {
                    authType: "subscriptionKey",
                    subscriptionKey: " <Your Azure Maps Key> "
                }
            });

            // Wait until the map resources are ready.
            map.events.add("ready", (event) => {
                // Create a custom layer to render data points using deck.gl
                map.layers.add(
                    new DeckGLLayer({
                        id: "grid-layer",
                        data: "https://raw.githubusercontent.com/visgl/deck.gl-data/master/website/sf-bike-parking.json",
                        cellSize: 200,
                        extruded: true,
                        elevationScale: 4,
                        getPosition: (d) => d.COORDINATES,
                        // GPUGridLayer leverages WebGL2 to perform aggregation on the GPU.
                        // For more details, see https://deck.gl/docs/api-reference/aggregation-layers/gpu-grid-layer
                        type: deck.GPUGridLayer
                    })
                );
            });

            // A custom implementation of WebGLLayer
            class DeckGLLayer extends atlas.layer.WebGLLayer {
                constructor(options) {
                    super(options.id);
                    // Create an instance of deck.gl MapboxLayer which is compatible with Azure Maps
                    // https://deck.gl/docs/api-reference/mapbox/mapbox-layer
                    this._mbLayer = new deck.MapboxLayer(options);

                    // Create a renderer
                    const renderer = {
                        renderingMode: "3d",
                        onAdd: (map, gl) => {
                            this._mbLayer.onAdd?.(map["map"], gl);
                        },
                        onRemove: (map, gl) => {
                            this._mbLayer.onRemove?.(map["map"], gl);
                        },
                        prerender: (gl, matrix) => {
                            this._mbLayer.prerender?.(gl, matrix);
                        },
                        render: (gl, matrix) => {
                            this._mbLayer.render(gl, matrix);
                        }
                    };
                    this.setOptions({ renderer });
                }
            }
        </script>
    </body>    
</html>

3D 地形底圖

從 Azure 地圖服務 Web SDK 3.0 開始,開發人員可以利用 3D 地形視覺效果。 這項功能可讓您將標高資料併入地圖中,為您的使用者創造更沉浸式的體驗。 無論是將山區範圍、山谷或其他地理特徵視覺化,3D 地形支援都為您的地圖應用程式帶來新的真實感層次。

下列程式碼範例示範如何實作 3D 地形底圖。

<!DOCTYPE html>
<html lang="en">
    <head>
        <meta charset="utf-8" />
        <meta name="viewport" content="width=device-width, user-scalable=no" />
        <title>Elevation - Azure Maps Web SDK Samples</title>
        <link href="https://atlas.microsoft.com/sdk/javascript/mapcontrol/3/atlas.min.css rel="stylesheet" />
        <script src="https://atlas.microsoft.com/sdk/javascript/mapcontrol/3/atlas.min.js></script>
        <style>
            html,
            body {
                width: 100%;
                height: 100%;
                padding: 0;
                margin: 0;
            }
            #map {
                width: 100%;
                height: 100%;
            }
        </style>
    </head>

    <body>
        <div id="map"></div>
        <script>
            var map = new atlas.Map("map", {
                center: [-121.7269, 46.8799],
                maxPitch: 85,
                pitch: 60,
                zoom: 12,
                style: "road_shaded_relief",
                // Get an Azure Maps key at https://azuremaps.com/.
                authOptions: {
                    authType: "subscriptionKey",
                    subscriptionKey: "<Your Azure Maps Key>"
                }
            });

            // Create a tile source for elevation data. For more information on creating
            // elevation data & services using open data, see https://aka.ms/elevation
            var elevationSource = new atlas.source.ElevationTileSource("elevation", {
                url: "<tileSourceUrl>"
            });

            // Wait until the map resources are ready.
            map.events.add("ready", (event) => {

                // Add the elevation source to the map.
                map.sources.add(elevationSource);

                // Enable elevation on the map.
                map.enableElevation(elevationSource);
            });
        </script>
    </body>
</html>

Azure Government 雲端支援

Azure 地圖服務 Web SDK 支援 Azure Government 雲端。 用來存取 Azure 地圖服務 Web SDK 的所有 JavaScript 和 CSS URL 都會維持不變。 您必須完成下列工作,才能連線到 Azure 地圖服務平台的 Azure Government 雲端版本。

使用互動式地圖控制項時,請先新增下列一行程式碼,再建立 Map 類別的執行個體。

atlas.setDomain('atlas.azure.us');

驗證地圖和服務時,請務必使用來自 Azure Government 雲端平台的 Azure 地圖服務驗證詳細資料。

JavaScript 架構

如果使用 JavaScript 架構進行開發,下列其中一個開放原始碼專案可能會很有用:

下一步

了解如何建立地圖並與其互動:

了解如何設定地圖的樣式:

了解最佳做法並查看範例:

如需示範如何將 Microsoft Entra ID 與 Azure 地圖服務整合的範例清單,請參閱: