マップに検索結果を表示する

この記事では、目的地を検索し、地図上に検索結果を表示する方法について説明します。

目的地の検索には、2 つ方法があります。 1 つの方法は、TypeScript REST SDK の @azure-rest/maps-search を使用して検索要求を行う方法です。 もう 1 つの方法は、Fetch API から Azure Maps Fuzzy Search API に対して検索要求を行うという方法です。 どちらの方法も、この記事内で説明します。

REST SDK を使用して検索要求を行う

import * as atlas from "azure-maps-control";
import MapsSearch from "@azure-rest/maps-search";
import "azure-maps-control/dist/atlas.min.css";

const onload = () => {
  // Initialize a map instance.
  const map = new atlas.Map("map", {
    view: "Auto",
    // Add authentication details for connecting to Azure Maps.
    authOptions: {
      // Use Azure Active Directory authentication.
      authType: "aad",
      clientId: "<Your Azure Maps Client Id>",
      aadAppId: "<Your Azure Active Directory Client Id>",
      aadTenant: "<Your Azure Active Directory Tenant Id>"
    }
  });

  map.events.add("load", async () => {
    // Use the access token from the map and create an object that implements the TokenCredential interface.
    const credential = {
      getToken: () => {
        return {
          token: map.authentication.getToken()
        };
      }
    };

    // Create a Search client.
    const client = MapsSearch(credential, "<Your Azure Maps Client Id>");

    // Create a data source and add it to the map.
    const datasource = new atlas.source.DataSource();
    map.sources.add(datasource);

    // Add a layer for rendering point data.
    const resultLayer = new atlas.layer.SymbolLayer(datasource);
    map.layers.add(resultLayer);

    // Search for gas stations near Seattle.
    const response = await client.path("/search/fuzzy/{format}", "json").get({
      queryParameters: {
        query: "gasoline station",
        lat: 47.6101,
        lon: -122.34255
      }
    });

    // Arrays to store bounds for results.
    const bounds = [];

    // Convert the response into Feature and add it to the data source.
    const searchPins = response.body.results.map((result) => {
      const position = [result.position.lon, result.position.lat];
      bounds.push(position);
      return new atlas.data.Feature(new atlas.data.Point(position), {
        position: result.position.lat + ", " + result.position.lon
      });
    });

     // Add the pins to the data source.
    datasource.add(searchPins);

    // Set the camera to the bounds of the pins
    map.setCamera({
      bounds: new atlas.data.BoundingBox.fromLatLngs(bounds),
      padding: 40
    });
  });
};

document.body.onload = onload;

上記のコード例において、最初のブロックはマップ オブジェクトを構築し、Microsoft Entra ID を使用するための認証メカニズムを設定します。 詳細については、「マップの作成」を参照してください。

2 つ目のコード ブロックはアクセス トークンを使用して Azure Maps に対して HTTP 要求を認証するための TokenCredential インターフェイスを実装するオブジェクトを作成します。 その後、資格情報オブジェクトを MapsSearch に渡し、クライアントのインスタンスを作成します。

2 つ目のコード ブロックでは、DataSource クラスを使用してデータ ソース オブジェクトが作成され、検索結果がそこに追加されます。 シンボル レイヤーは、テキストまたはアイコンを使用して、DataSource にラップされたポイントベースのデータをシンボルとしてマップにレンダリングします。 シンボル レイヤーが作成されます。 データ ソースがシンボル レイヤーに追加され、それがマップに追加されます。

4 番目のコード ブロックは、MapsSearch クライアントで GET 要求を行います。 それにより、Get Search Fuzzy rest API を介して自由形式のテキスト検索を実行して、POI を検索できます。 Get requests to the Search Fuzzy API では、どの組み合わせのあいまい入力も処理できます。 その後、応答は Feature オブジェクトに変換され、データ ソースに追加されます。これにより、データがシンボル レイヤーを介してマップ上に自動でレンダリングされます。

最後のコード ブロックでは、マップの setCamera プロパティを使用してマップのカメラ境界が調整されます。

検索要求、データ ソース、シンボル レイヤー、カメラの境界は、マップのイベント リスナー内にあります。 必ず、マップが完全に読み込まれた後に、結果が表示されるようにします。

Fetch API を使用して検索要求を行う

import * as atlas from "azure-maps-control";
import "azure-maps-control/dist/atlas.min.css";

const onload = () => {
  // Initialize a map instance.
  const map = new atlas.Map("map", {
    view: "Auto",
    // Add authentication details for connecting to Azure Maps.
    authOptions: {
      // Use Azure Active Directory authentication.
      authType: "aad",
      clientId: "<Your Azure Maps Client Id>",
      aadAppId: "<Your Azure Active Directory Client Id>",
      aadTenant: "<Your Azure Active Directory Tenant Id>"
    }
  });

  map.events.add("load", () => {
    // Create a data source and add it to the map.
    const datasource = new atlas.source.DataSource();
    map.sources.add(datasource);

    // Add a layer for rendering point data.
    const resultLayer = new atlas.layer.SymbolLayer(datasource);
    map.layers.add(resultLayer);

    // Send a request to Azure Maps search API
    let url = "https://atlas.microsoft.com/search/fuzzy/json?";
    url += "&api-version=1";
    url += "&query=gasoline%20station";
    url += "&lat=47.6101";
    url += "&lon=-122.34255";
    url += "&radius=100000";

    // Parse the API response and create a pin on the map for each result
    fetch(url, {
      headers: {
        Authorization: "Bearer " + map.authentication.getToken(),
        "x-ms-client-id": "<Your Azure Maps Client Id>"
      }
    })
      .then((response) => response.json())
      .then((response) => {
        // Arrays to store bounds for results.
        const bounds = [];

        // Convert the response into Feature and add it to the data source.
        const searchPins = response.results.map((result) => {
          const position = [result.position.lon, result.position.lat];
          bounds.push(position);
          return new atlas.data.Feature(new atlas.data.Point(position), {
            position: result.position.lat + ", " + result.position.lon
          });
        });

        // Add the pins to the data source.
        datasource.add(searchPins);

        // Set the camera to the bounds of the pins
        map.setCamera({
          bounds: new atlas.data.BoundingBox.fromLatLngs(bounds),
          padding: 40
        });
      });
  });
};

document.body.onload = onload;

前のコード例では、最初のコード ブロックはマップ オブジェクトを構築します。 Microsoft Entra ID を使用する認証メカニズムを設定します。 詳細については、「マップの作成」を参照してください。

2 つ目のコード ブロックは、DataSource クラスを使用してデータ ソース オブジェクトを作成し、検索結果をそこに追加します。 シンボル レイヤーは、テキストまたはアイコンを使用して、DataSource にラップされたポイントベースのデータをシンボルとしてマップにレンダリングします。 シンボル レイヤーが作成されます。 データ ソースがシンボル レイヤーに追加され、それがマップに追加されます。

3 番目のコード ブロックは、検索要求を行う URL を作成します。

4 番目のコード ブロックは、Fetch API を使用します。 Fetch API は、Azure Maps Fuzzy Search API に対して要求を行って目的地を検索するために使用されます。 あいまい検索 API は、あいまい入力の任意の組み合わせを処理できます。 次に、検索応答の処理と解析を行い、結果のピンを searchPins 配列に追加します。

最後のコード ブロックでは、BoundingBox オブジェクトが作成されます。 結果の配列が使用され、その後、マップの setCamera を使用してマップに対するカメラ境界が調整されます。 次に、結果のピンがレンダリングされます。

必ずマップの読み込みが完了した後に結果が表示されるように、マップのイベント リスナー内で検索要求、データ ソース、シンボル レイヤー、およびカメラ境界が設定されます。

次の図は、2 つのコード サンプルの結果を示すスクリーンショットです。

A screenshot of search results showing gas stations near Seattle.

次のステップ

あいまい検索の詳細については、こちらを参照してください。

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

Map

完全なコードの例については、次の記事を参照してください。