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

教程:使用 Azure Maps 搜索附近兴趣点

本教程演示如何为 Azure Maps 设置帐户,然后使用 Maps API 搜索兴趣点。 在本教程中,你将了解如何执行以下操作:

  • 创建 Azure Maps 帐户
  • 检索 Maps 帐户的订阅密钥
  • 使用 Map Control API 创建新网页
  • 使用 Maps 搜索服务查找附近的兴趣点

先决条件

如果没有 Azure 订阅,请在开始之前创建一个免费帐户

注意

有关 Azure Maps 中身份验证的详细信息,请参阅在 Azure Maps 中管理身份验证

创建新地图

Map Control API 是一个便利的客户端库。 使用此 API,可以轻松将 Maps 集成到你的 Web 应用程序中。 它消除了单纯 REST 服务调用的复杂性,并可以通过可自定义的组件提高工作效率。 以下步骤说明如何使用 Map Control API 创建一个嵌入式静态 HTML 页面。

  1. 在本地计算机上,创建一个新文件并将其命名为 MapSearch.html

  2. 将以下 HTML 组件添加到该文件:

     <!DOCTYPE html>
     <html>
     <head>
         <title>Map Search</title>
         <meta charset="utf-8" />
    
         <!-- Add references to the Azure Maps Map control JavaScript and CSS files. -->
         <link rel="stylesheet" href="https://atlas.microsoft.com/sdk/javascript/mapcontrol/3/atlas.min.css" type="text/css" />
         <script src="https://atlas.microsoft.com/sdk/javascript/mapcontrol/3/atlas.min.js"></script>
    
         <script>
         function GetMap(){
             //Add Map Control JavaScript code here.
         }
         </script>
    
         <style>
             html,
             body {
                 width: 100%;
                 height: 100%;
                 padding: 0;
                 margin: 0;
             }
    
             #myMap {
                 width: 100%;
                 height: 100%;
             }
         </style>
     </head>
     <body onload="GetMap()">
         <div id="myMap"></div>
     </body>
     </html>
    

    有关上述 HTML 的一些信息:

    • HTML 标头包含 Azure Map Control 库托管的 CSS 和 JavaScript 资源文件。
    • 当页面正文加载时,页面正文中的 onload 事件会调用 GetMap 函数。
    • GetMap 函数包含用于访问 Azure Maps API 的内联 JavaScript 代码。 下一步将添加它。
  3. 将以下 JavaScript 代码添加到 HTML 文件的 GetMap 函数。 将字符串 <Your Azure Maps Subscription Key> 替换为从 Azure Maps 帐户复制的订阅密钥。

    //Instantiate a map object
    var map = new atlas.Map("myMap", {
        view: 'Auto',
    
        // Add your Azure Maps subscription key. https://aka.ms/am-primaryKey
        authOptions: {
            authType: 'subscriptionKey',
            subscriptionKey: '<Your Azure Maps Subscription Key>'
        }
    });
    

    有关上述 JavaScript 的一些信息:

    • 这是 GetMap 函数的核心,可为 Azure Maps 帐户密钥初始化 Map Control API。
    • atlas 是包含 API 和相关视觉对象组件的命名空间。
    • atlas.Map 提供视觉对象和交互式 Web 地图的控件。
  4. 将更改保存到文件并在浏览器中打开 HTML 页。 所显示的地图是使用帐户密钥调用 atlas.Map 所能生成的最基本的地图。

    显示了可以通过使用 Azure Maps 帐户密钥调用 atlas.Map 生成的最基本的地图。

  5. GetMap 函数中,请在初始化地图以后,添加以下 JavaScript 代码。

    //Wait until the map resources are ready.
    map.events.add('ready', function() {
    
        //Create a data source and add it to the map.
        datasource = new atlas.source.DataSource();
        map.sources.add(datasource);
    
        //Add a layer for rendering point data.
        var resultLayer = new atlas.layer.SymbolLayer(datasource, null, {
            iconOptions: {
                image: 'pin-round-darkblue',
                anchor: 'center',
                allowOverlap: true
            },
            textOptions: {
                anchor: "top"
            }
        });
    
        map.layers.add(resultLayer);
    });
    

    关于此代码:

    • 向地图添加 ready 事件,当地图资源完成加载且地图已准备好被访问时,将触发该事件。
    • 在地图 ready 事件处理程序中,将会创建一个数据源来存储结果数据。
    • 将会创建一个符号层并将其附加到数据源。 此层指定应当如何呈现数据源中的结果数据。 在本例中,结果将使用深蓝色圆形图钉图标呈现,该图标位于结果坐标的中心,并允许其他图标重叠。
    • 结果层将添加到地图层。

添加搜索功能

本部分演示如何使用 Maps Search API 在地图上查找兴趣点。 这是一个 RESTful API,可让开发人员搜索地址、兴趣点和其他地理信息。 搜索服务会将纬度和经度信息分配到指定的地址。

提示

Azure Maps 为 Azure Maps JavaScript REST SDK 提供了一组 npm 模块。 这些模块包括可简化在 Node.js 应用程序中使用 Azure Maps REST 服务的客户端库。 如需可用模块的完整列表,请参阅 JavaScript/TypeScript REST SDK 开发人员指南(预览版)

搜索服务

  1. 在映射 ready 事件处理程序中添加以下脚本块。 这是生成搜索查询的代码。 它使用模糊搜索服务,这是搜索服务的基本搜索 API。 模糊搜索服务可处理最模糊的输入,例如地址、位置和兴趣点 (POI)。 此代码在提供的经纬度的指定半径内搜索邻近的加油站。 然后提取 GeoJSON 特征集合,并将其添加到数据源,这将自动在地图符号层上呈现数据。 脚本块的最后一部分使用地图的 setCamera 属性通过结果的边框设置地图相机视图。

    var query = 'gasoline-station';
    var radius = 9000;
    var lat = 47.64452336193245;
    var lon = -122.13687658309935;
    var url = `https://atlas.microsoft.com/search/poi/json?api-version=1.0&query=${query}&lat=${lat}&lon=${lon}&radius=${radius}`;
    
    fetch(url, {
        headers: {
            "Subscription-Key": map.authentication.getToken()
        }
    })
    .then((response) => response.json())
    .then((response) => {
        var bounds = [];
    
        //Extract GeoJSON feature collection from the response and add it to the datasource
        var data = response.results.map((result) => {
            var position = [result.position.lon, result.position.lat];
            bounds.push(position);
            return new atlas.data.Feature(new atlas.data.Point(position), { ...result });
        });
        datasource.add(data);
    
        //Set camera to bounds to show the results
        map.setCamera({
            bounds: new atlas.data.BoundingBox.fromLatLngs(bounds),
            zoom: 10,
            padding: 15
        });
    });
    
  2. 保存“MapSearch.html”文件并刷新浏览器 。 你应当会看到地图以西雅图为中心,蓝色的圆形图钉标记了该区域中加油站的位置。

    屏幕截图显示搜索结果地图,该地图显示西雅图地区,蓝色的圆形图钉标记了加油站的位置。

  3. 在浏览器中输入以下 HTTPRequest,即可看到地图呈现的原始数据。 将 <Your Azure Maps Subscription Key> 替换为订阅密钥。

    https://atlas.microsoft.com/search/poi/json?api-version=1.0&query=gasoline%20station&subscription-key={Your-Azure-Maps-Subscription-key}&lat=47.6292&lon=-122.2337&radius=100000
    

此时,MapSearch 页可显示模糊搜索查询返回的兴趣点的位置。 让我们添加一些交互功能和有关位置的详细信息。

添加交互式数据

现在为止已完成的地图仅显示搜索结果的经度/纬度数据。 但是,Maps 搜索服务返回的原始 JSON 包含有关每个加油站的其他信息。 包括名称和街道地址。 可以使用交互式弹出框将数据合并到地图。

  1. 在地图 ready 事件处理程序中,在用于查询模糊搜索服务的代码后面添加以下代码行。 此代码会创建弹出窗口的实例,并向符号层添加鼠标悬停事件。

    // Create a popup but leave it closed so we can update it and display it later.
    popup = new atlas.Popup();
    
    //Add a mouse over event to the result layer and display a popup when this event fires.
    map.events.add('mouseover', resultLayer, showPopup);
    

    API atlas.Popup 提供一个固定在地图上所需位置的信息窗口。

  2. 在代码后的地图 ready 事件处理程序中添加以下代码行,以创建弹出窗口的实例,并向符号层添加鼠标悬停事件。 将鼠标悬停在兴趣点上时,此代码会显示一个带有结果的弹出窗口。

    function showPopup(e) {
        //Get the properties and coordinates of the first shape that the event occurred on.
    
        var p = e.shapes[0].getProperties();
        var position = e.shapes[0].getCoordinates();
    
        //Create HTML from properties of the selected result.
        var html = `
          <div style="padding:5px">
            <div><b>${p.poi.name}</b></div>
            <div>${p.address.freeformAddress}</div>
            <div>${position[1]}, ${position[0]}</div>
          </div>`;
    
        //Update the content and position of the popup.
        popup.setPopupOptions({
            content: html,
            position: position
        });
    
        //Open the popup.
        popup.open(map);
    }
    
  3. 保存文件并刷新浏览器。 现在,将鼠标悬停在任何搜索图钉上时,浏览器中的地图会显示信息弹出窗口。

    屏幕截图显示将鼠标悬停在搜索图钉上时,地图显示信息弹出窗口。

  • 有关本教程中使用的完整代码,请参阅 GitHub 上的搜索教程
  • 若要实时查看此示例,请参阅 Azure Maps 代码示例站点上的搜索兴趣点

后续步骤

下一教程演示如何显示两个地点之间的路线。