教學課程:使用 Azure 地圖服務來搜尋附近景點

本教學課程說明如何使用 Azure 地圖服務來設定帳戶,然後使用地圖服務 API 來搜尋景點。 在本教學課程中,您會了解如何:

  • 建立 Azure 地圖服務帳戶
  • 擷取地圖服務帳戶的訂用帳戶金鑰
  • 使用地圖控制項 API 建立新的網頁
  • 使用地圖服務的搜尋服務來尋找附近景點

必要條件

如果您沒有 Azure 訂用帳戶,請在開始前建立免費帳戶

注意

如需 Azure 地圖服務中驗證的詳細資訊,請參閱管理 Azure 地圖服務中的驗證

建立新的地圖

地圖控制項 API 是一個方便的用戶端程式庫。 此 API 可讓您輕鬆地將地圖服務整合到 Web 應用程式中。 它會隱藏裸機 REST 服務呼叫的複雜度,並使用可自訂的元件提升您的生產力。 下列步驟顯示如何建立內嵌地圖控制項 API 的靜態 HTML 網頁。

  1. 在您的本機機器上建立新檔案,並將其命名為 MapSearch.html

  2. 在檔案中新增下列 HTML 元件:

     <!DOCTYPE html>
     <html>
     <head>
         <title>Map Search</title>
         <meta charset="utf-8" />
    
         <!-- 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>
    
         <!-- Add a reference to the Azure Maps Services Module JavaScript file. -->
         <script src="https://atlas.microsoft.com/sdk/javascript/service/2/atlas-service.min.js"></script>
    
         <script>
         function GetMap(){
             //Add Map Control JavaScript code here.
         }
         </script>
    
         <style>
             html,
             body {
                 width: 100%;
                 height: 100%;
                 padding: 0;
                 margin: 0;
             }
    
             #myMap {
                 width: 100%;
                 height: 100%;
             }
         </style>
     </head>
     <body onload="GetMap()">
         <div id="myMap"></div>
     </body>
     </html>
    

    關於上述 HTML 的一些須知:

    • HTML 標頭包含 Azure 地圖控制項程式庫裝載的 CSS 和 JavaScript 資源檔。
    • 頁面主體載入後,頁面主體的 onload 事件會呼叫 GetMap 函式。
    • GetMap 函式包含內嵌 JavaScript 程式碼,可用來存取 Azure 地圖服務 API。 下一個步驟會新增此函式。
  3. 在 HTML 檔案的 GetMap 函式中新增下列 JavaScript 程式碼。 從 Azure 地圖服務帳戶複製訂用帳戶金鑰後,取代字串 <Your Azure Maps Subscription Key>

    //Instantiate a map object
    var map = new atlas.Map("myMap", {
        view: 'Auto',
    
        // Add your Azure Maps subscription key. https://aka.ms/am-primaryKey
        authOptions: {
            authType: 'subscriptionKey',
            subscriptionKey: '<Your Azure Maps Subscription Key>'
        }
    });
    

    關於上述 JavaScript 的一些須知:

    • GetMap 函式的核心,會將 Azure 地圖服務帳戶金鑰的地圖控制項 API 初始化。
    • atlas 是包含 API 和相關視覺效果元件的命名空間。
    • atlas.Map 可供控制視覺化互動式網路地圖。
  4. 將變更儲存至檔案,並在瀏覽器中開啟 HTML 網頁。 顯示的地圖是您可以藉由呼叫 atlas.Map 和使用帳戶金鑰來建立的最基本地圖。

    螢幕快照,顯示您可以呼叫 『atlas』 進行的最基本地圖。使用 Azure 地圖服務 帳戶金鑰進行對應。

  5. GetMap 函式中,在地圖完成初始化之後新增下列 JavaScript 程式碼。

    //Wait until the map resources are ready.
    map.events.add('ready', function() {
    
        //Create a data source and add it to the map.
        datasource = new atlas.source.DataSource();
        map.sources.add(datasource);
    
        //Add a layer for rendering point data.
        var resultLayer = new atlas.layer.SymbolLayer(datasource, null, {
            iconOptions: {
                image: 'pin-round-darkblue',
                anchor: 'center',
                allowOverlap: true
            },
            textOptions: {
                anchor: "top"
            }
        });
    
        map.layers.add(resultLayer);
    });
    

    關於此程式碼:

    • ready 事件會新增至地圖,並在地圖資源完成載入且可存取後引發。
    • 在地圖 ready 事件處理常式中,會建立資料來源以儲存結果資料。
    • 系統會建立符號圖層,並將其附加至資料來源。 此圖層會指定結果資料在資料來源中的呈現方式。 在此案例中,結果以結果座標中間的深藍色圓形圖釘圖示呈現,並允許其他圖示重疊。
    • 結果圖層會新增至地圖圖層。

新增搜尋功能

本節說明如何使用「地圖服務」的搜尋 API在地圖上尋找景點。 這是針對開發人員所設計的 RESTful API,用於搜尋地址、景點及其他地理資訊。 搜尋服務會將經緯度資訊指派給指定的地址。 下一個說明的服務模組可讓您使用地圖服務搜尋 API 來搜尋位置。

注意

Azure 地圖服務 Web SDK 服務模組淘汰

Azure 地圖服務 Web SDK 服務模組現已淘汰,將於 9/30/26 淘汰。 若要避免服務中斷,建議您以 9/30/26 移轉至 Azure 地圖服務 JavaScript REST SDK。 如需詳細資訊,請參閱 JavaScript/TypeScript REST SDK 開發人員指南(預覽版)。

服務模組

  1. 在地圖 ready 事件處理常式中,在 map.layers.add(resultLayer); 後方新增下列 JavaScript 程式碼,即可建構搜尋服務 URL:

    //Use MapControlCredential to share authentication between a map control and the service module.
    var pipeline = atlas.service.MapsURL.newPipeline(new atlas.service.MapControlCredential(map));
    
    // Construct the SearchURL object
    var searchURL = new atlas.service.SearchURL(pipeline); 
    
  2. 接著,在地圖 ready 事件處理常式之前新增的程式碼下,新增下列指令碼區塊。 這是組建搜尋查詢的程式碼。 此程式碼使用模糊搜尋服務,即搜尋服務的基本搜尋 API。 模糊搜尋服務可處理大部分的模糊輸入,例如地址、地點和景點 (POI)。 此程式碼會在所提供經緯度指定的半徑範圍內,搜尋附近的加油站。 接著使用 geojson.getFeatures() 方法從回應擷取 GeoJSON 功能集合,並新增至資料來源,同時在地圖符號圖層轉譯的資料自動產生結果。 指令碼區塊的最後一個部分會使用結果的周框方塊,亦即使用地圖的 setCamera 屬性,設定地圖相機檢視。

    var query = 'gasoline-station';
    var radius = 9000;
    var lat = 47.64452336193245;
    var lon = -122.13687658309935;
    
    searchURL.searchPOI(atlas.service.Aborter.timeout(10000), query, {
        limit: 10,
        lat: lat,
        lon: lon,
        radius: radius,
        view: 'Auto'
    }).then((results) => {
    
        // Extract GeoJSON feature collection from the response and add it to the datasource
        var data = results.geojson.getFeatures();
        datasource.add(data);
    
        // set camera to bounds to<Your Azure Maps Subscription Key> show the results
        map.setCamera({
            bounds: data.bbox,
            zoom: 10,
            padding: 15
        });
    });
    
  3. 儲存 MapSearch.html 檔案並重新整理瀏覽器。 您應該會看到西雅圖為中心的地圖,以藍色圓形圖釘表示該區域中的加油站位置。

    此螢幕快照顯示搜尋所產生的地圖,這是地圖,顯示西雅圖在加油站位置有圓藍色圖釘。

  4. 您可以在瀏覽器中輸入下列 HTTPRequest,以查看地圖所呈現的原始資料。 將 <Your Azure Maps Subscription Key> 取代為訂用帳戶金鑰。

    https://atlas.microsoft.com/search/poi/json?api-version=1.0&query=gasoline%20station&subscription-key={Your-Azure-Maps-Subscription-key}&lat=47.6292&lon=-122.2337&radius=100000
    

至此,MapSearch 網頁可顯示模糊搜尋查詢所傳回的景點位置。 讓我們新增一些互動式功能和位置的詳細資訊。

新增互動式資料

我們到目前為止所建立的地圖只會查看搜尋結果的經緯度資料。 但地圖服務的搜尋服務所傳回的原始 JSON 會包含每個加油站的其他資訊。 包括名稱和街道地址在內。 您可以使用互動式快顯方塊將該資料合併到地圖中。

  1. 在查詢模糊搜尋服務的程式碼後面,在地圖 ready 事件處理常式中新增以下幾行程式碼。 此程式碼將建立快顯視窗的執行個體,並將滑鼠停駐事件新增至符號圖層。

    // Create a popup but leave it closed so we can update it and display it later.
    popup = new atlas.Popup();
    
    //Add a mouse over event to the result layer and display a popup when this event fires.
    map.events.add('mouseover', resultLayer, showPopup);
    

    API atlas.Popup 可提供錨定在地圖上所需位置的資訊視窗。

  2. 在程式碼後方新增下列地圖 ready 事件處理常式的程式碼,建立 Popup 的執行個體,並新增 mouseover 事件至符號圖層。 滑鼠停留在景點上方時,此程式碼會顯示包含結果的快顯視窗。

    function showPopup(e) {
        //Get the properties and coordinates of the first shape that the event occurred on.
    
        var p = e.shapes[0].getProperties();
        var position = e.shapes[0].getCoordinates();
    
        //Create HTML from properties of the selected result.
        var html = `
          <div style="padding:5px">
            <div><b>${p.poi.name}</b></div>
            <div>${p.address.freeformAddress}</div>
            <div>${position[1]}, ${position[0]}</div>
          </div>`;
    
        //Update the content and position of the popup.
        popup.setPopupOptions({
            content: html,
            position: position
        });
    
        //Open the popup.
        popup.open(map);
    }
    
  3. 儲存檔案並重新整理瀏覽器。 滑鼠目前停留在任何搜尋圖釘上時,瀏覽器中的地圖會立即顯示資訊快顯。

    地圖的螢幕快照,其中包含當您將滑鼠停留在搜尋釘選上時所顯示的信息彈出視窗。

  • 如需本教學課程中使用的完整程式碼,請參閱 GitHub 上的搜尋 (英文) 教學課程。
  • 若要即時檢視此範例,請參閱在 Azure 地圖服務程式碼範例網站上搜尋景點

下一步

下一個教學課程會示範如何顯示兩個位置之間的路線。