次の方法で共有


Azure Maps サービス モジュールを使用する

Azure Maps Web SDK には 、サービス モジュールが用意されています。 このモジュールは、Web または Node.js アプリケーションから JavaScript または TypeScript を使用して簡単に Azure Maps REST サービスを使用できるようにするヘルパー ライブラリです。

Azure Maps Web SDK サービス モジュールの廃止

Azure Maps Web SDK サービス モジュールは非推奨になりました。また、2026 年 9 月 30 日に廃止される予定です。 サービスの中断を回避するために、2026 年 9 月 30 日までに Azure Maps JavaScript REST SDK に移行することをお勧めします。 詳細については、「JavaScript/TypeScript REST SDK 開発者ガイド (プレビュー)」を参照してください。

Web ページでサービス モジュールを使用する

  1. 新しい HTML ファイルを作成します。

  2. Azure Maps サービス モジュールを読み込みます。 次の 2 つの方法のいずれかで読み込むことができます。

    • グローバルにホストされている Azure Maps サービス モジュールの Azure Content Delivery Network のバージョンを使用します。 ファイルの <head> 要素にスクリプト参照を追加します。
    <script src="https://atlas.microsoft.com/sdk/javascript/service/2/atlas-service.min.js"></script>
    
    • または、 azure-maps-rest npm パッケージを使用して Azure Maps Web SDK ソース コードのサービス モジュールをローカルに読み込み、アプリでホストします。 このパッケージには TypeScript 定義も含まれています。 次のコマンドを実行します。

      npm install azure-maps-rest

      次に、インポート宣言を使用してモジュールをソース ファイルに追加します。

      import * as service from "azure-maps-rest";
      
  3. 認証パイプラインを作成します。 サービス URL クライアント エンドポイントを初期化する前に、パイプラインを作成する必要があります。 Azure Maps Search サービス クライアントを認証するには、独自の Azure Maps アカウント キーまたは Microsoft Entra 資格情報を使用します。 この例では、Search サービス 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 Maps での認証」を参照してください。

  4. 次のコードでは、新しく作成された Azure Maps Search サービス 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 Maps Web SDK では、Azure Government クラウドがサポートされています。 Azure Maps Web SDK にアクセスするために使用されるすべての JavaScript と CSS URL は変わりませんが、Azure Maps プラットフォームの Azure Government クラウド バージョンに接続するには、次のタスクを実行する必要があります。

対話型マップ コントロールを使用する場合は、Map クラスのインスタンスを作成する前に、次のコード行を追加します。

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

マップとサービスを認証するときは、必ず Azure Government クラウド プラットフォームの Azure Maps 認証の詳細を使用してください。

API URL エンドポイントのインスタンスを作成するときは、サービスのドメインを設定する必要があります。 たとえば、次のコードは、 SearchURL クラスのインスタンスを作成し、ドメインを Azure Government クラウドにポイントします。

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

Azure Maps REST サービスに直接アクセスする場合は、URL ドメインを atlas.azure.us に変更します。 たとえば、検索 API サービスを使用する場合は、URL ドメインを https://atlas.microsoft.com/search/ から https://atlas.azure.us/search/ に変更します。

次のステップ

この記事で使われているクラスとメソッドの詳細については、次を参照してください。

サービス モジュールを使用するその他のコード サンプルについては、次の記事を参照してください。