JavaScript/TypeScript REST SDK 開発者ガイド (プレビュー)

Azure Maps JavaScript/TypeScript REST SDK (JavaScript SDK) では、住所の検索、都市または国の境界の検索、座標による検索など、Azure Maps Search Service を使用した検索がサポートされています。 この記事は、Azure Maps の機能が組み込まれた位置情報認識アプリケーションの構築を開始するのに役立ちます。

Note

Azure Maps JavaScript SDK では、Node.js の LTS バージョンがサポートされています。 詳細については、Node.js リリースの作業グループに関するページを参照してください。

前提条件

ヒント

Azure Maps アカウントはプログラムで作成できます。Azure CLI を使用した例を次に示します。

az maps account create --kind "Gen2" --account-name "myMapAccountName" --resource-group "<resource group>" --sku "G2"

Node.js プロジェクトを作成する

次の例では、新しいディレクトリを作成した後、npm を使用して mapsDemo という名前の Node.js プログラムを作成します。

mkdir mapsDemo
cd mapsDemo
npm init

検索パッケージをインストールする

Azure Maps JavaScript SDK を使用するには、検索パッケージをインストールする必要があります。 検索、ルーティング、レンダリング、位置情報を含む各 Azure Maps サービスは、それぞれ独自のパッケージに含まれています。

npm install @azure-rest/maps-search

パッケージがインストールされたら、mapsDemo ディレクトリに search.js ファイルを作成します。

mapsDemo
+-- package.json
+-- package-lock.json
+-- node_modules/
+-- search.js

Azure Maps サービス

[サービス名] npm パッケージ サンプル
検索する @azure-rest/maps-search 検索サンプル
Route @azure-rest/maps-route ルート サンプル
レンダリング @azure-rest/maps-render レンダリング サンプル
位置情報 @azure-rest/maps-geolocation 位置情報サンプル

MapsSearchClient の作成と認証

Azure Maps Search API にアクセスするために使用される MapsSearchClient オブジェクトを作成するときに、認証用の credential オブジェクトが必要になります。 認証には、Microsoft Entra 資格情報または Azure サブスクリプション キーを使用できます。 認証の詳細については、「Azure Maps による認証」を参照してください。

ヒント

MapsSearchClient は、Azure Maps の検索ライブラリを使用する開発者向けのプライマリ インターフェイスです。 使用可能な検索方法の詳細については、Azure Maps の検索ライブラリに関するページを参照してください。

Microsoft Entra 資格情報の使用

Azure ID ライブラリを使用して、Microsoft Entra ID で認証できます。 DefaultAzureCredential プロバイダーを使用するには、@azure/identity パッケージをインストールする必要があります。

npm install @azure/identity

サービス プリンシパルに必要なロールを割り当てて、新しい Microsoft Entra アプリケーションを登録するとともに Azure Maps へのアクセス権を付与する必要があります。 詳細については、「Azure 以外のリソースでデーモンをホストする」を参照してください。 アプリケーション (クライアント) ID、ディレクトリ (テナント) ID、クライアント シークレットが返されます。 これらの値をコピーし、安全な場所に保存します。 これらは、次の手順で必要になります。

次のように、お使いの Microsoft Entra アプリケーションのアプリケーション (クライアント) ID、ディレクトリ (テナント) ID、クライアント シークレット、さらに Map リソースのクライアント ID の値を環境変数として設定します。

環境変数 説明
AZURE_CLIENT_ID 登録したアプリケーションのアプリケーション (クライアント) ID
AZURE_CLIENT_SECRET 登録したアプリケーションのクライアント シークレットの値
AZURE_TENANT_ID 登録したアプリケーションのディレクトリ (テナント) ID
MAPS_CLIENT_ID Azure Map アカウントのクライアント ID

これらの変数には .env ファイルを使用できます。 dotenv パッケージをインストールする必要があります。

npm install dotenv

次に、mapsDemo ディレクトリに .env ファイルを追加し、次のプロパティを指定します。

AZURE_CLIENT_ID="<client-id>"
AZURE_CLIENT_SECRET="<client-secret>"
AZURE_TENANT_ID="<tenant-id>"
MAPS_CLIENT_ID="<maps-client-id>"

環境変数が作成されたら、JavaScript コードでアクセスできます。

const MapsSearch = require("@azure-rest/maps-search").default; 
const { DefaultAzureCredential } = require("@azure/identity"); 
require("dotenv").config(); 
 
const credential = new DefaultAzureCredential(); 
const client = MapsSearch(credential, process.env.MAPS_CLIENT_ID); 

サブスクリプション キー資格情報の使用

Azure Maps サブスクリプション キーを使用して認証できます。 以下のスクリーンショットに示されているように、サブスクリプション キーは Azure Maps アカウントの [認証] セクションに表示されます。

Screenshot showing your Azure Maps subscription key in the Azure portal.

Azure Core 認証パッケージによって提供される AzureKeyCredential クラスにサブスクリプション キーを渡す必要があります。 セキュリティ上の理由から、このキーはソース コードに含めるよりも、環境変数として指定することをお勧めします。

これを行うには、.env ファイルを使用してサブスクリプション キー変数を格納します。 この値を取得するには、dotenv パッケージをインストールする必要があります。

npm install dotenv

次に、mapsDemo ディレクトリに .env ファイルを追加し、次のプロパティを指定します。

MAPS_SUBSCRIPTION_KEY="<subscription-key>"

環境変数が作成されたら、以下のように JavaScript コードでアクセスできます。

const MapsSearch = require("@azure-rest/maps-search").default;
const { AzureKeyCredential } = require("@azure/core-auth");
require("dotenv").config();

const credential = new AzureKeyCredential(process.env.MAPS_SUBSCRIPTION_KEY);
const client = MapsSearch(credential);

Shared Access Signature (SAS) トークン資格情報の使用

Shared Access Signature (SAS) トークンは、JSON Web トークン (JWT) 形式を使用して作成された認証トークンであり、Azure Maps REST API に対するアプリケーションの認証を証明するために暗号化され署名されます。

SAS トークンは、AzureMapsManagementClient.accounts.listSas パッケージを使用して取得できます。 最初に、セクション「AzureMapsManagementClient の作成と認証」に従ってセットアップを行います。

次に、「Azure Maps 用のマネージド ID」に従って、Azure Maps アカウント用のマネージド ID を作成します。 マネージド ID のプリンシパル ID (オブジェクト ID) をコピーします。

次に、AzureSASCredential を使用するために、Azure Core Authentication Package パッケージをインストールします。

npm install @azure/core-auth

最後に、SAS トークンを使用してクライアントを認証できます。

  const MapsSearch = require("@azure-rest/maps-search").default;
  const { AzureSASCredential } = require("@azure/core-auth");
  const { DefaultAzureCredential } = require("@azure/identity");
  const { AzureMapsManagementClient } = require("@azure/arm-maps");

  const subscriptionId = "<subscription ID of the map account>"
  const resourceGroupName = "<resource group name of the map account>";
  const accountName = "<name of the map account>";
  const mapsAccountSasParameters = {
    start: "<start time in ISO format>", // e.g. "2023-11-24T03:51:53.161Z"
    expiry: "<expiry time in ISO format>", // maximum value to start + 1 day
    maxRatePerSecond: 500,
    principalId: "<principle ID (object ID) of the managed identity>",
    signingKey: "primaryKey",
  };
  const credential = new DefaultAzureCredential();
  const managementClient = new AzureMapsManagementClient(credential, subscriptionId);
  const {accountSasToken} = await managementClient.accounts.listSas(
    resourceGroupName,
    accountName,
    mapsAccountSasParameters
  );
  if (accountSasToken === undefined) {
    throw new Error("No accountSasToken was found for the Maps Account.");
  }
  const sasCredential = new AzureSASCredential(accountSasToken);
  const client = MapsSearch(sasCredential);

ジオコーディング

次のコード スニペットは、単純なコンソール アプリケーションで @azure-rest/maps-search パッケージをインポートし、GetGeocoding クエリを使用して住所の座標を取得します。

const MapsSearch = require("@azure-rest/maps-search").default;
const { isUnexpected } = require("@azure-rest/maps-search");
const { AzureKeyCredential } = require("@azure/core-auth");
require("dotenv").config();

async function main() {
  const credential = new AzureKeyCredential(
    process.env. MAPS_SUBSCRIPTION_KEY
  );
  const client = MapsSearch(credential);

  const response = await client.path("/geocode", "json").get({
    queryParameters: {
      query: "1301 Alaskan Way, Seattle, WA 98101, US",
    },
  });
  if (isUnexpected(response)) {
    throw response.body.error;
  }
  const [ lon, lat ] = response.body.features[0].geometry.coordinates;
  console.log(`The coordinate is: (${lat}, ${lon})`);
}

main().catch((err) => {
  console.error(err);
});

このコード スニペットは、Azure Maps Search クライアント ライブラリの MapsSearch メソッドを使用して、Azure 資格情報で client オブジェクトを作成する方法を示しています。 Azure Maps サブスクリプション キーまたは Microsoft Entra 資格情報のいずれかを使用できます。 path パラメーターは API エンドポイントを指定します。この場合は "/geocode" です。 get メソッドでは、クエリ パラメーターを指定して HTTP GET 要求を送信します。 このクエリは、"1301 Alaskan Way, Seattle, WA 98101, US" の座標を検索します。 SDK は、結果を GeocodingResponseOutput オブジェクトとして返し、コンソールに書き込みます。 この例では、結果を信頼度スコア順に並べ替え、最初の結果のみが画面に表示されます。 詳細については、「GetGeocoding」を参照してください。

Node.js で search.js を実行します。

node search.js 

バッチ逆ジオコーディング

Azure Maps Search には、いくつかのバッチ クエリ メソッドも用意されています。 次の例は、バッチ処理された逆引き検索メソッドを呼び出す方法を示しています。

  const batchItems = [
    // This is an invalid query
    { coordinates: [2.294911, 148.858561] },
    {
      coordinates: [-122.34255, 47.6101],
    },
    { coordinates: [-122.33817, 47.6155] },
  ];
  const response = await client.path("/reverseGeocode:batch").post({
    body: { batchItems },
  });

この例では、要求本文の batchItems に 3 つの座標が含まれています。 最初の項目は無効です。無効な項目の処理方法を示す例については、「失敗した要求の処理」を参照してください。

応答を取得したら、ログに記録できます。

 
function logResponseBody(resBody) {
  const { summary, batchItems } = resBody;

  const { totalRequests, successfulRequests } = summary;
  console.log(`${successfulRequests} out of ${totalRequests} requests are successful.`);

  batchItems.forEach(({ response }, idx) => {
    if (response.error) {
      console.log(`Error in ${idx + 1} request: ${response.error.message}`);
    } else {
      console.log(`Results in ${idx + 1} request:`);
      response.features.forEach((feature) => {
        console.log(`  ${feature.properties.address.freeformAddress}`);
      });
    }
  });
} 

失敗した要求の処理

応答バッチ項目の error プロパティをチェックして、失敗した要求を処理します。 完成したバッチ逆引き検索の次の例にある logResponseBody 関数を参照してください。

完成したバッチ逆引き検索の例

住所のバッチ逆引き検索の完成したコード:

const MapsSearch = require("@azure-rest/maps-search").default,
  { isUnexpected } = require("@azure-rest/maps-search");
const { AzureKeyCredential } = require("@azure/core-auth");
require("dotenv").config();

async function main() {
  const credential = new AzureKeyCredential(process.env.MAPS_SUBSCRIPTION_KEY);
  const client = MapsSearch(credential);

  const batchItems = [
    // This is an invalid query
    { coordinates: [2.294911, 148.858561] },
    {
      coordinates: [-122.34255, 47.6101],
    },
    { coordinates: [-122.33817, 47.6155] },
  ];

  const response = await client.path("/reverseGeocode:batch").post({
    body: { batchItems },
  });

  if (isUnexpected(response)) {
    throw response.body.error;
  }

  logResponseBody(resumeResponse.body);
}

function logResponseBody(resBody) {
  const { summary, batchItems } = resBody;

  const { totalRequests, successfulRequests } = summary;
  console.log(`${successfulRequests} out of ${totalRequests} requests are successful.`);

  batchItems.forEach(({ response }, idx) => {
    if (response.error) {
      console.log(`Error in ${idx + 1} request: ${response.error.message}`);
    } else {
      console.log(`Results in ${idx + 1} request:`);
      response.features.forEach((feature) => {
        console.log(`  ${feature.properties.address.freeformAddress}`);
      });
    }
  });
} 

main().catch(console.error);

V1 SDK を使用する

Microsoft では、V1 のすべての機能を V2 で利用できるように取り組んでいます。それまでは、必要に応じて次の V1 SDK パッケージをインストールしてください。

npm install @azure-rest/map-search-v1@npm:@azure-rest/map-search@^1.0.0
npm install @azure-rest/map-search-v2@npm:@azure-rest/map-search@^2.0.0

次に、次の 2 つのパッケージをインポートできます。

const MapsSearchV1 = require("@azure-rest/map-search-v1").default;
const MapsSearchV2 = require("@azure-rest/map-search-v2").default;

次の例は、住所を受け取り、その周辺の POI を検索する関数の作成例を示しています。 V2 SDK を使用して、住所の座標 (/geocode) を取得し、V1 SDK を使用して、その周囲の POI (/search/nearby) を検索します。

const MapsSearchV1 = require("@azure-rest/map-search-v1").default;
const MapsSearchV2 = require("@azure-rest/map-search-v2").default;
const { AzureKeyCredential } = require("@azure/core-auth");
const { isUnexpected: isUnexpectedV1 } = require("@azure-rest/maps-search-v1");
const { isUnexpected: isUnexpectedV2 } = require("@azure-rest/maps-search-v2");
require("dotenv").config();

/** Initialize the MapsSearchClient */
const clientV1 = MapsSearchV1(new AzureKeyCredential(process.env.MAPS_SUBSCRIPTION_KEY));
const clientV2 = MapsSearchV2(new AzureKeyCredential(process.env.MAPS_SUBSCRIPTION_KEY));

async function searchNearby(address) {
  /** Make a request to the geocoding API */
  const geocodeResponse = await clientV2
    .path("/geocode")
    .get({ queryParameters: { query: address } });
  /** Handle error response */
  if (isUnexpectedV2(geocodeResponse)) {
    throw geocodeResponse.body.error;
  }

  const [lon, lat] = geocodeResponse.body.features[0].geometry.coordinates;
  
  /** Make a request to the search nearby API */
  const nearByResponse = await clientV1.path("/search/nearby/{format}", "json").get({
    queryParameters: { lat, lon },
  });
  /** Handle error response */
  if (isUnexpectedV1(nearByResponse)) {
    throw nearByResponse.body.error;
  }
  /** Log response body */
  for(const results of nearByResponse.body.results) {
    console.log(
      `${result.poi ? result.poi.name + ":" : ""} ${result.address.freeformAddress}. (${
        result.position.lat
      }, ${result.position.lon})\n`
    );
  }
}

async function main(){
  searchNearBy("15127 NE 24th Street, Redmond, WA 98052");
}

main().catch((err) => {
    console.log(err);
})

追加情報