使用 Azure 地圖服務 服務模組

Azure 地圖服務 Web SDK 提供服務模組。 本課程模組是協助程序連結庫,可讓您使用 JavaScript 或 TypeScript,輕鬆地在 Web 或Node.js應用程式中使用 Azure 地圖服務 REST 服務。

注意

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

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

在網頁中使用服務模組

  1. 建立新的 HTML 檔案。

  2. 載入 Azure 地圖服務 服務模組。 您可以透過下列兩種方式之一載入它:

    • 使用全域裝載的 Azure 內容傳遞網路版 Azure 地圖服務模組。 將文稿參考新增至 <head> 檔案的 元素:
    <script src="https://atlas.microsoft.com/sdk/javascript/service/2/atlas-service.min.js"></script>
    
    • 或者,使用 azure-maps-rest npm 套件,在本機載入 Azure 地圖服務 Web SDK 原始程式碼的服務模組,然後將它裝載於您的應用程式。 此套件也包含 TypeScript 定義。 使用此命令:

      npm install azure-maps-rest

      然後,使用匯入宣告,將模組新增至來源檔案:

      import * as service from "azure-maps-rest";
      
  3. 建立驗證管線。 您必須先建立管線,才能初始化服務 URL 用戶端端點。 使用您自己的 Azure 地圖服務 帳戶密鑰或 Microsoft Entra 認證來驗證 Azure 地圖服務 搜尋服務 用戶端。 在此範例中,會建立 搜尋服務 URL 用戶端。

    如果您使用訂用帳戶金鑰進行驗證:

    // Get an Azure Maps key at https://azure.com/maps.
    var subscriptionKey = '<Your Azure Maps Key>';
    
    // Use SubscriptionKeyCredential with a subscription key.
    var subscriptionKeyCredential = new atlas.service.SubscriptionKeyCredential(subscriptionKey);
    
    // Use subscriptionKeyCredential to create a pipeline.
    var pipeline = atlas.service.MapsURL.newPipeline(subscriptionKeyCredential, {
      retryOptions: { maxTries: 4 } // Retry options
    });
    
    // Create an instance of the SearchURL client.
    var searchURL = new atlas.service.SearchURL(pipeline);
    

    如果您使用 Microsoft Entra ID 進行驗證:

    // Enter your Azure AD client ID.
    var clientId = "<Your Azure Active Directory Client Id>";
    
    // Use TokenCredential with OAuth token (Azure AD or Anonymous).
    var aadToken = await getAadToken();
    var tokenCredential = new atlas.service.TokenCredential(clientId, aadToken);
    
    // Create a repeating time-out that will renew the Azure AD token.
    // This time-out must be cleared when the TokenCredential object is no longer needed.
    // If the time-out is not cleared, the memory used by the TokenCredential will never be reclaimed.
    var renewToken = async () => {
      try {
        console.log("Renewing token");
        var token = await getAadToken();
        tokenCredential.token = token;
        tokenRenewalTimer = setTimeout(renewToken, getExpiration(token));
      } catch (error) {
        console.log("Caught error when renewing token");
        clearTimeout(tokenRenewalTimer);
        throw error;
      }
    }
    tokenRenewalTimer = setTimeout(renewToken, getExpiration(aadToken));
    
    // Use tokenCredential to create a pipeline.
    var pipeline = atlas.service.MapsURL.newPipeline(tokenCredential, {
      retryOptions: { maxTries: 4 } // Retry options
    });
    
    // Create an instance of the SearchURL client.
    var searchURL = new atlas.service.SearchURL(pipeline);
    
    function getAadToken() {
      // Use the signed-in auth context to get a token.
      return new Promise((resolve, reject) => {
        // The resource should always be https://atlas.microsoft.com/.
        const resource = "https://atlas.microsoft.com/";
        authContext.acquireToken(resource, (error, token) => {
          if (error) {
            reject(error);
          } else {
            resolve(token);
          }
        });
      })
    }
    
    function getExpiration(jwtToken) {
      // Decode the JSON Web Token (JWT) to get the expiration time stamp.
      const json = atob(jwtToken.split(".")[1]);
      const decode = JSON.parse(json);
    
      // Return the milliseconds remaining until the token must be renewed.
      // Reduce the time until renewal by 5 minutes to avoid using an expired token.
      // The exp property is the time stamp of the expiration, in seconds.
      const renewSkew = 300000;
      return (1000 * decode.exp) - Date.now() - renewSkew;
    }
    

    如需詳細資訊,請參閱使用 Azure 地圖服務 進行驗證。

  4. 下列程式代碼會使用新建立的 Azure 地圖服務 搜尋服務 URL 用戶端來地理編碼位址:「1 Microsoft Way,Redmond, WA」。 程序代碼會使用 函式, searchAddress 並將結果顯示為頁面主體中的數據表。

    // Search for "1 microsoft way, redmond, wa".
    searchURL.searchAddress(atlas.service.Aborter.timeout(10000), '1 microsoft way, redmond, wa')
      .then(response => {
        var html = [];
    
        // Display the total results.
        html.push('Total results: ', response.summary.numResults, '<br/><br/>');
    
        // Create a table of the results.
        html.push('<table><tr><td></td><td>Result</td><td>Latitude</td><td>Longitude</td></tr>');
    
        for(var i=0;i<response.results.length;i++){
          html.push('<tr><td>', (i+1), '.</td><td>', 
            response.results[i].address.freeformAddress, 
            '</td><td>', 
            response.results[i].position.lat,
            '</td><td>', 
            response.results[i].position.lon,
            '</td></tr>');
        }
    
        html.push('</table>');
    
        // Add the resulting HTML to the body of the page.
        document.body.innerHTML = html.join('');
    });
    

以下是完整的執行程式碼範例:

<html>
 <head>

  <script src="https://atlas.microsoft.com/sdk/javascript/service/2/atlas-service.min.js"></script>

  <script type="text/javascript">
    
    // Get an Azure Maps key at https://azure.com/maps.
    var subscriptionKey = '{Your-Azure-Maps-Subscription-key}';

    // Use SubscriptionKeyCredential with a subscription key.
    var subscriptionKeyCredential = new atlas.service.SubscriptionKeyCredential(subscriptionKey);

    // Use subscriptionKeyCredential to create a pipeline.
    var pipeline = atlas.service.MapsURL.newPipeline(subscriptionKeyCredential, {
      retryOptions: { maxTries: 4 } // Retry options
    });

    // Create an instance of the SearchURL client.
    var searchURL = new atlas.service.SearchURL(pipeline);

    // Search for "1 microsoft way, redmond, wa".
    searchURL.searchAddress(atlas.service.Aborter.timeout(10000), '1 microsoft way, redmond, wa')
      .then(response => {
      var html = [];

      // Display the total results.
      html.push('Total results: ', response.summary.numResults, '<br/><br/>');

      // Create a table of the results.
      html.push('<table><tr><td></td><td>Result</td><td>Latitude</td><td>Longitude</td></tr>');

      for(var i=0;i<response.results.length;i++){
        html.push('<tr><td>', (i+1), '.</td><td>', 
        response.results[i].address.freeformAddress, 
        '</td><td>', 
        response.results[i].position.lat,
        '</td><td>', 
        response.results[i].position.lon,
        '</td></tr>');
      }

      html.push('</table>');

      // Add the resulting HTML to the body of the page.
      document.body.innerHTML = html.join('');
    });

  </script>
</head>

<style>
  table {
    border: 1px solid black;
    border-collapse: collapse;
  }
  td, th {
    border: 1px solid black;
    padding: 5px;
  }
</style>

<body> </body>

</html>

下圖是螢幕快照,其中顯示此範例程式代碼的結果、搜尋地址的數據表,以及產生的座標。

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 地圖服務 驗證詳細數據。

建立 API URL 端點的實例時,必須設定服務的網域。 例如,下列程式代碼會建立 類別的 SearchURL 實例,並將網域指向 Azure Government 雲端。

var searchURL = new atlas.service.SearchURL(pipeline, 'atlas.azure.us');

如果直接存取 Azure 地圖服務 REST 服務,請將網址變更為 atlas.azure.us。 例如,如果使用搜尋 API 服務,請將網址從 https://atlas.microsoft.com/search/ 變更為 https://atlas.azure.us/search/

下一步

深入了解本文使用的類別和方法:

如需使用服務模組的更多程式碼範例,請參閱下列文章: