您现在访问的是微软AZURE全球版技术文档网站,若需要访问由世纪互联运营的MICROSOFT AZURE中国区技术文档网站,请访问 https://docs.azure.cn.

教程:使用 Azure Maps 搜索附近兴趣点Tutorial: Search nearby points of interest using Azure Maps

本教程演示如何为 Azure Maps 设置帐户,然后使用 Maps API 搜索兴趣点。This tutorial shows how to set up an account with Azure Maps, then use the Maps APIs to search for a point of interest. 在本教程中,你将了解如何执行以下操作:In this tutorial, you learn how to:

  • 创建 Azure Maps 帐户Create an Azure Maps account
  • 检索 Maps 帐户的主要密钥Retrieve the primary key for your Maps account
  • 使用 Map Control API 创建新网页Create a new web page using the map control API
  • 使用 Maps 搜索服务查找附近的兴趣点Use the Maps search service to find a nearby point of interest

先决条件Prerequisites

  1. 登录 Azure 门户Sign in to the Azure portal. 如果没有 Azure 订阅,请在开始之前创建一个免费帐户If you don't have an Azure subscription, create a free account before you begin.
  2. 创建 Azure Maps 帐户Make an Azure Maps account
  3. 获取主订阅密钥(亦称为“主密钥”或“订阅密钥”)。Obtain a primary subscription key, also known as the primary key or the subscription key. 有关 Azure Maps 中身份验证的详细信息,请参阅在 Azure Maps 中管理身份验证For more information on authentication in Azure Maps, see manage authentication in Azure Maps.

创建新地图Create a new map

Map Control API 是一个便利的客户端库。The Map Control API is a convenient client library. 使用此 API,可以轻松将 Maps 集成到你的 Web 应用程序中。This API allows you to easily integrate Maps into your web application. 它消除了单纯 REST 服务调用的复杂性,并可以通过可自定义的组件提高工作效率。It hides the complexity of the bare REST service calls and boosts your productivity with customizable components. 以下步骤说明如何使用 Map Control API 创建一个嵌入式静态 HTML 页面。The following steps show you how to create a static HTML page embedded with the Map Control API.

  1. 在本地计算机上,创建一个新文件并将其命名为 MapSearch.htmlOn your local machine, create a new file and name it MapSearch.html .

  2. 将以下 HTML 组件添加到该文件:Add the following HTML components to the file:

     <!DOCTYPE html>
     <html>
     <head>
         <title>Map Search</title>
         <meta charset="utf-8">
         <meta name="viewport" content="width=device-width, initial-scale=1, shrink-to-fit=no">
    
         <!-- Add references to the Azure Maps Map control JavaScript and CSS files. -->
         <link rel="stylesheet" href="https://atlas.microsoft.com/sdk/javascript/mapcontrol/2/atlas.min.css" type="text/css">
         <script src="https://atlas.microsoft.com/sdk/javascript/mapcontrol/2/atlas.min.js"></script>
    
         <!-- Add a reference to the Azure Maps Services Module JavaScript file. -->
         <script src="https://atlas.microsoft.com/sdk/javascript/service/2/atlas-service.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 标头包含 Azure 地图控件库托管的 CSS 和 JavaScript 资源文件。Notice that the HTML header includes the CSS and JavaScript resource files hosted by the Azure Map Control library. 请注意页面正文中的 onload 事件。当页面正文加载时,此事件会调用 GetMap 函数。Note the onload event on the body of the page, which will call the GetMap function when the body of the page has loaded. GetMap 函数将包含内联的 JavaScript 代码,以访问 Azure Maps API。The GetMap function will contain the inline JavaScript code to access the Azure Maps APIs.

  3. 将以下 JavaScript 代码添加到 HTML 文件的 GetMap 函数。Add the following JavaScript code to the GetMap function of the HTML file. 将字符串 <Your Azure Maps Key> 替换为从 Maps 帐户复制的主密钥。Replace the string <Your Azure Maps Key> with the primary key that you copied from your Maps account.

    //Instantiate a map object
    var map = new atlas.Map("myMap", {
        //Add your Azure Maps subscription key to the map SDK. Get an Azure Maps key at https://azure.com/maps
        authOptions: {
            authType: 'subscriptionKey',
            subscriptionKey: '<Your Azure Maps Key>'
        }
    });
    

    此段为 Azure Maps 帐户密钥初始化地图控件 API。This segment initializes the Map Control API for your Azure Maps account key. atlas 是包含 API 和相关视觉对象组件的命名空间。atlas is the namespace that contains the API and related visual components. atlas.Map 提供视觉对象和交互式 Web 地图的控件。atlas.Map provides the control for a visual and interactive web map.

  4. 将更改保存到文件并在浏览器中打开 HTML 页。Save your changes to the file and open the HTML page in a browser. 所显示的地图是使用帐户密钥调用 atlas.Map 所能生成的最基本的地图。The map shown is the most basic map that you can make by calling atlas.Map using your account key.

    查看地图

  5. GetMap 函数中,请在初始化地图以后,添加以下 JavaScript 代码。In the GetMap function, after initializing the map, add the following JavaScript code.

    //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 事件。当地图资源加载以后,该事件会触发,然后地图就可以供用户访问。In this code segment, a ready event is added to the map, which will fire when the map resources have been loaded and the map is ready to be accessed. 在地图 ready 事件处理程序中,将会创建一个数据源来存储结果数据。In the map ready event handler, a data source is created to store result data. 将会创建一个符号层并将其附加到数据源。A symbol layer is created and attached to the data source. 此层指定应当如何呈现数据源中的结果数据。This layer specifies how the result data in the data source should be rendered. 在本例中,结果将使用深蓝色圆形图钉图标呈现,该图标位于结果坐标的中心,并允许其他图标重叠。In this case, the result is rendered with a dark blue round pin icon, centered over the results coordinate, and allows other icons to overlap. 结果层将添加到地图层。The result layer is added to the map layers.

添加搜索功能Add search capabilities

本部分演示如何使用 Maps Search API 在地图上查找兴趣点。This section shows how to use the Maps Search API to find a point of interest on your map. 这是一个 RESTful API,可让开发人员搜索地址、兴趣点和其他地理信息。It's a RESTful API designed for developers to search for addresses, points of interest, and other geographical information. 搜索服务会将纬度和经度信息分配到指定的地址。The Search service assigns a latitude and longitude information to a specified address. 下面介绍的“服务模块”可以用来通过地图搜索 API 搜索位置。The Service Module explained below can be used to search for a location using the Maps Search API.

服务模块Service Module

  1. 在地图 ready 事件处理程序中,添加以下 JavaScript 代码来构造搜索服务 URL。In the map ready event handler, construct the search service URL by adding the following JavaScript code.

    // Use SubscriptionKeyCredential with a subscription key
    var subscriptionKeyCredential = new atlas.service.SubscriptionKeyCredential(atlas.getSubscriptionKey());
    
    // Use subscriptionKeyCredential to create a pipeline
    var pipeline = atlas.service.MapsURL.newPipeline(subscriptionKeyCredential);
    
    // Construct the SearchURL object
    var searchURL = new atlas.service.SearchURL(pipeline); 
    

    SubscriptionKeyCredential 创建 SubscriptionKeyCredentialPolicy 以使用订阅密钥验证对 Azure Maps 的 HTTP 请求。The SubscriptionKeyCredential creates a SubscriptionKeyCredentialPolicy to authenticate HTTP requests to Azure Maps with the subscription key. atlas.service.MapsURL.newPipeline() 接受 SubscriptionKeyCredential 策略并创建管道实例。The atlas.service.MapsURL.newPipeline() takes in the SubscriptionKeyCredential policy and creates a Pipeline instance. searchURL 表示 Azure Maps 搜索操作的 URL。The searchURL represents a URL to Azure Maps Search operations.

  2. 接下来添加以下脚本块,以便生成搜索查询。Next add the following script block to build the search query. 它使用模糊搜索服务,这是搜索服务的基本搜索 API。It uses the Fuzzy Search Service, which is a basic search API of the Search Service. 模糊搜索服务可处理最模糊的输入,例如地址、位置和兴趣点 (POI)。Fuzzy Search Service handles most fuzzy inputs like addresses, places, and points of interest (POI). 此代码在提供的经纬度的指定半径内搜索邻近的加油站。This code searches for nearby Gasoline Stations within the specified radius of the provided latitude and longitude. 然后使用 geojson.getFeatures() 方法提取响应中的 GeoJSON 特征集合,并将其添加到数据源,这将自动通过符号层在地图上呈现数据。A GeoJSON feature collection from the response is then extracted using the geojson.getFeatures() method and added to the data source, which automatically results in the data being rendered on the map via the symbol layer. 脚本的最后一部分使用地图的 setCamera 属性通过结果的边框设置地图相机视图。The last part of the script sets the maps camera view using the bounding box of the results using the Map's setCamera property.

    var query =  'gasoline-station';
    var radius = 9000;
    var lat = 47.64452336193245;
    var lon = -122.13687658309935;
    
    searchURL.searchPOI(atlas.service.Aborter.timeout(10000), query, {
        limit: 10,
        lat: lat,
        lon: lon,
        radius: radius
    }).then((results) => {
    
        // Extract GeoJSON feature collection from the response and add it to the datasource
        var data = results.geojson.getFeatures();
        datasource.add(data);
    
        // set camera to bounds to show the results
        map.setCamera({
            bounds: data.bbox,
            zoom: 10
        });
    });
    
  3. 保存“MapSearch.html”文件并刷新浏览器 。Save the MapSearch.html file and refresh your browser. 你应当会看到地图以西雅图为中心,蓝色的圆形图钉标记了该区域中加油站的位置。You should see the map centered on Seattle with round-blue pins for locations of gasoline stations in the area.

    查看包含搜索结果的地图

  4. 在浏览器中输入以下 HTTPRequest,即可看到地图呈现的原始数据。You can see the raw data that the map is rendering by entering the following HTTPRequest in your browser. 将 <Your Azure Maps Key> 替换为主密钥。Replace <Your Azure Maps Key> with your primary key.

    https://atlas.microsoft.com/search/poi/json?api-version=1.0&query=gasoline%20station&subscription-key=<subscription-key>&lat=47.6292&lon=-122.2337&radius=100000
    

此时,MapSearch 页可显示模糊搜索查询返回的兴趣点的位置。At this point, the MapSearch page can display the locations of points of interest that are returned from a fuzzy search query. 让我们添加一些交互功能和有关位置的详细信息。Let's add some interactive capabilities and more information about the locations.

添加交互式数据Add interactive data

现在为止已完成的地图仅显示搜索结果的经度/纬度数据。The map that we've made so far only looks at the longitude/latitude data for the search results. 但是,Maps 搜索服务返回的原始 JSON 包含有关每个加油站的其他信息。However, the raw JSON that the Maps Search service returns contains additional information about each gas station. 包括名称和街道地址。Including the name and street address. 可以使用交互式弹出框将数据合并到地图。You can incorporate that data into the map with interactive popup boxes.

  1. 在地图 ready 事件处理程序中,在用于查询模糊搜索服务的代码后面添加以下代码行。Add the following lines of code in the map ready event handler after the code to query the fuzzy search service. 此代码将创建弹出窗口的实例,并向符号层添加鼠标悬停事件。This code will create an instance of a Popup and add a mouseover event to the symbol layer.

    //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 提供一个固定在地图上所需位置的信息窗口。The API *atlas.Popup provides an information window anchored at the required position on the map.

  2. GetMap 函数中添加以下代码,以便在弹出窗口中显示鼠标悬停结果信息。Add the following code within the GetMap function, to show the moused over result information in the popup.

    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. 保存文件并刷新浏览器。Save the file and refresh your browser. 现在,将鼠标悬停在任何搜索图钉上时,浏览器中的地图显示信息弹出窗口。Now the map in the browser shows information pop-ups when you hover over any of the search pins.

    Azure 地图控件和搜索服务

若要查看本教程的完整代码,请单击此处To view the full code for this tutorial, click here. 若要查看实时示例,请单击此处To view the live sample, click here

后续步骤Next steps

下一教程演示如何显示两个地点之间的路线。The next tutorial demonstrates how to display a route between two locations.