你当前正在访问 Microsoft Azure Global Edition 技术文档网站。 如果需要访问由世纪互联运营的 Microsoft Azure 中国技术文档网站,请访问 https://docs.azure.cn

在地图上显示搜索结果

本文介绍如何搜索感兴趣的位置并在地图上显示搜索结果。

可通过两种方法来搜索感兴趣的位置。 一种方法是使用 TypeScript REST SDK @azure-rest/maps-search 发出搜索请求。 另一种方法是通过提取 API 向 Azure Maps 模糊搜索 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。 有关详细信息,请参阅创建地图

第二个代码块创建了对象,该对象实现 TokenCredential 接口,通过访问令牌验证对 Azure Maps 的 HTTP 请求。 然后,它将凭据对象传递给 MapsSearch 并创建客户端的实例。

第三个代码块使用 DataSource 类创建一个数据源对象并向其添加搜索结果。 某个符号层使用文本或图标来呈现作为符号包装在地图上 DataSource 中的基于点的数据。 随后创建符号层。 将数据源添加到符号层,然后将符号层添加到地图。

第四个代码块在 MapsSearch 客户端中发出了 GET 请求。 它允许通过获取模糊搜索 REST API 执行自由格式文本搜索,以搜索兴趣点。 模糊搜索 API 的获取请求可以处理任何模糊输入组合。 然后,响应会解析成要素对象并添加到数据源,从而自动通过符号层在地图上呈现数据。

最后一个代码块使用地图的 setCamera 属性调整地图的照相机边界。

搜索请求、数据源、符号层和照相机边界位于地图的事件侦听器内。 我们想要确保结果在地图完全加载后显示。

通过提取 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。 有关详细信息,请参阅创建地图

第二个代码块使用 DataSource 类创建了一个数据源对象并向其添加了搜索结果。 某个符号层使用文本或图标来呈现作为符号包装在地图上 DataSource 中的基于点的数据。 随后创建符号层。 将数据源添加到符号层,然后将符号层添加到地图。

第三个代码块创建了一个可向其发出搜索请求的 URL。

第四个代码块使用了提取 API提取 API 用于向 Azure Maps 模糊搜索 API 发出兴趣点搜索请求。 模糊搜索 API 可以处理任意组合的模糊输入。 然后,它会处理并分析搜索响应,并将结果图钉添加到 searchPins 数组。

最后一个代码块创建 BoundingBox 对象。 它使用结果数组,然后使用地图的 setCamera 为地图调整照相机边界。 随后呈现结果图钉。

在地图的事件侦听器中设置搜索请求、数据源、符号层以及照相机边界,以确保结果在地图完全加载后显示。

下图是一个屏幕截图,显示了两个代码示例的结果。

A screenshot of search results showing gas stations near Seattle.

后续步骤

详细了解模糊搜索

详细了解本文中使用的类和方法:

Map

有关完整代码示例,请参阅以下文章: