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

教程:使用 Azure Maps 查找和显示不同出行模式的路线Tutorial: Find and display routes for different modes of travel using Azure Maps

本教程演示如何使用 Azure Maps 路线服务地图控件为私家车和货物类型为 USHazmatClass2 的商用车(卡车)显示路线走向。This tutorial shows you how to use the Azure Maps Route service and Map control to display route directions for both private vehicles and commercial vehicles (trucks) with USHazmatClass2 cargo type . 此外,我们还将演示如何在地图上直观呈现实时交通数据。In addition, we'll walk you through how to visualize real-time traffic data on a map. 在本教程中,你将了解如何执行以下操作:In this tutorial, you learn how to:

  • 在网页上创建和显示地图控件Create and display the Map control on a web page
  • 在地图上呈现实时交通数据Render real-time traffic data on a map
  • 在地图上请求并显示私家车和商用车路线Request and display private and commercial vehicle routes on a map

先决条件Prerequisites

  1. 登录 Azure 门户Sign in to the Azure portal.

  2. 创建 Azure Maps 帐户Create 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.

可在此处获得示例的完整源代码。You can obtain the full source code for the sample here. 可在此处找到实时示例。A live sample can be found here.

使用 Map Control API 创建新网页Create a new web page using the map control API

以下步骤演示如何在网页中创建和显示地图控件。The following steps show you how to create and display the Map control in a web page.

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

  2. 将以下 HTML 标记复制/粘贴到文件中。Copy/paste the following HTML markup into the file.

    <!DOCTYPE html>
    <html>
    <head>
        <title>Map Route</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>
            var map, datasource, client;
    
            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 Map Control 库托管的 CSS 和 JavaScript 资源文件。The HTML header includes the CSS and JavaScript resource files hosted by the Azure Map Control library. 正文的 onload 事件调用 GetMap 函数。The body's onload event calls the GetMap function. 在下一步中,我们将添加地图控件初始化代码。In the next step, we'll add the Map control initialization code.

  3. 将以下 JavaScript 代码添加到 GetMap 函数。Add the following JavaScript code to the GetMap function. 将字符串 <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>'
        }
    });
    
  4. 保存文件并在浏览器中打开它。Save the file and open it in your browser. 此时显示一个示例。A simple is displayed.

    地图控件的基本地图呈现

在地图上呈现实时交通数据Render real-time traffic data on a map

  1. GetMap 函数中追加以下 JavaScript 代码。Append the following JavaScript code in the GetMap function. 此代码实现地图控件的 ready 事件处理程序。This code implements the Map control's ready event handler. 本教程中的其余代码将放在 ready 事件处理程序中。The rest of the code in this tutorial will be placed inside the ready event handler.

    map.events.add("ready", function() {
        // Add Traffic Flow to the Map
        map.setTraffic({
            flow: "relative"
        });
    });
    

    在地图 ready 事件处理程序中,地图上的交通流设置已设置为 relative,这是相对于自由流动的道路速度。In the map ready event handler, the traffic flow setting on the map is set to relative, which is the speed of the road relative to free-flow. 有关更多交通选项,请参阅 TrafficOptions 接口For more traffic options, see TrafficOptions interface.

  2. 保存“MapTruckRoute.html”文件并刷新浏览器中的页 。Save the MapTruckRoute.html file and refresh the page in your browser. 如果放大地图并显示任何城市(如洛杉矶),你可看到显示了当前交通流数据的街道。If you zoom into any city, like Los Angeles, you will see that the streets display with current traffic flow data.

    在地图上查看交通信息

定义路线显示呈现Define route display rendering

在本教程中,将会计算两条线路并在地图上呈现它们。In this tutorial, two routes will be calculated and rendered on the map. 将为私家车(小汽车)计算第一条路线。The first route will be calculated for a private vehicle (car). 将为商用车(卡车)计算第二条路线,以显示结果之间的差异。The second route will be calculated for a commercial vehicle (truck) to show the difference between the results. 在呈现时,地图上将针对路线的起点和终点显示符号图标,用不同颜色的路线几何图形来表示各个路线路径。When rendered, the map will display a symbol icon for the start and end points of the route, and route line geometries with different colors for each route path. 有关添加线条层的详细信息,请参阅将线条层添加到地图For more information on adding line layers, see Add a line layer to a map. 若要了解有关符号层的详细信息,请参阅将符号层添加到地图To learn more about symbol layers, see Add a symbol layer to a map.

  1. 在地图控件的 ready 事件处理程序中,追加以下代码。In the Map control's ready event handler, append the following code.

    
    //Create a data source and add it to the map.
    datasource = new atlas.source.DataSource();
    map.sources.add(datasource);
    
    //Add a layer for rendering the route lines and have it render under the map labels.
    map.layers.add(new atlas.layer.LineLayer(datasource, null, {
        strokeColor: ['get', 'strokeColor'],
        strokeWidth: ['get', 'strokeWidth'],
        lineJoin: 'round',
        lineCap: 'round'
    }), 'labels');
    
    //Add a layer for rendering point data.
    map.layers.add(new atlas.layer.SymbolLayer(datasource, null, {
        iconOptions: {
            image: ['get', 'icon'],
            allowOverlap: true
        },
        textOptions: {
            textField: ['get', 'title'],
            offset: [0, 1.2]
        },
        filter: ['any', ['==', ['geometry-type'], 'Point'], ['==', ['geometry-type'], 'MultiPoint']] //Only render Point or MultiPoints in this layer.
    }));
    
    

    在地图控件的 ready 事件处理程序中,将会创建一个数据源来存储从起点到终点的路线。In the Map control's ready event handler, a data source is created to store the route from start to finish. 使用表达式从路线功能的属性中检索路线宽度和颜色。Expressions are used to retrieve the line width and color from properties on the route line feature. 为了确保路线线条不遮盖道路标签,我们传递了第二个参数,其值为 'labels'To ensure that the route line doesn't cover up the road labels, we've passed a second parameter with the value of 'labels'.

    接下来,将会创建一个符号层并将其附加到数据源。Next, a symbol layer is created and attached to the data source. 此层指定起点和终点的呈现方式。已添加表达式,用于从每个点对象的属性中检索图标图像和文本标签信息。This layer specifies how the start and end points are rendered.Expressions have been added to retrieve the icon image and text label information from properties on each point object. 若要详细了解表达式,请参阅数据驱动的样式表达式To learn more about expressions, see Data-driven style expressions.

  2. 将起点设为西雅图一家名为 Fabrikam 的虚构公司,终点设为 Microsoft 办公室。Set the start point as a fictitious company in Seattle called Fabrikam, and the end point as a Microsoft office. 在地图控件的 ready 事件处理程序中,追加以下代码。In the Map control's ready event handler, append the following code.

    //Create the GeoJSON objects which represent the start and end point of the route.
    var startPoint = new atlas.data.Feature(new atlas.data.Point([-122.356099, 47.580045]), {
        title: 'Fabrikam, Inc.',
        icon: 'pin-blue'
    });
    
    var endPoint = new atlas.data.Feature(new atlas.data.Point([-122.201164, 47.616940]), {
        title: 'Microsoft - Lincoln Square',
        icon: 'pin-round-blue'
    });
    
    //Add the data to the data source.
    datasource.add([startPoint, endPoint]);
    
    //Fit the map window to the bounding box defined by the start and end positions.
    map.setCamera({
        bounds: atlas.data.BoundingBox.fromData([startPoint, endPoint]),
        padding: 100
    });
    
    

    此代码创建两个 GeoJSON 点对象来表示起点和终点,这两个对象随后添加到数据源中。This code creates two GeoJSON Point objects to represent start and end points, which are then added to the data source.

    最后一个代码块使用起点和终点的纬度和经度来设置相机视图。The last block of code sets the camera view using the latitude and longitude of the start and end points. 起点和终点会添加到数据源。The start and end points are added to the data source. 起点和终点的边框使用 atlas.data.BoundingBox.fromData 函数计算。The bounding box for the start and end points is calculated using the atlas.data.BoundingBox.fromData function. 此边框用于通过 map.setCamera 函数设置基于整个路线的地图相机视图。This bounding box is used to set the map cameras view over the entire route using the map.setCamera function. 将会添加一个填充来弥补符号图标的像素尺寸。Padding is added to compensate for the pixel dimensions of the symbol icons. 有关地图控件的 setCamera 属性的详细信息,请参阅 setCamera(CameraOptions | CameraBoundsOptions & AnimationOptions) 属性。For more information about the Map control's setCamera property, see setCamera(CameraOptions | CameraBoundsOptions & AnimationOptions) property.

  3. 保存 TruckRoute.html 并刷新浏览器。Save TruckRoute.html and refresh your browser. 现在,地图以西雅图为中心。The map is now centered over Seattle. 泪珠形蓝色图钉标记起点。The teardrop blue pin marks the start point. 圆形蓝色图钉标记终点。The round blue pin marks the end point.

    查看有起点和终点的地图

在地图上请求并显示私家车和商用车路线Request and display private and commercial vehicle routes on a map

本部分演示如何使用 Azure Maps 路线服务,根据交通方式获取从一个点到另一个点的走向。This section shows you how to use the Azure Maps Route service to get directions from one point to another, based on your mode of transport. 我们将使用两种交通方式:卡车和小汽车。We'll be using two modes of transport: truck and car.

提示

路线服务提供多个 API,根据距离、路况和所用交通方式,规划最快、最短、环保或令人兴奋的路线 。The Route service provides APIs to plan fastest, shortest, eco, or thrilling routes based on distance, traffic conditions, and mode of transport used. 此服务还让用户可以根据历史路况规划将来的路线。The service also lets users plan future routes based on historical traffic conditions. 用户可以看到任何给定时间的路线时间预测。Users can see the prediction of route durations for any given time. 有关详细信息,请参阅获取路线走向 APIFor more information, see Get Route directions API.

  1. GetMap 函数的控件的 ready 事件处理程序中,将以下内容添加到 JavaScript 代码中。In the GetMap function, inside the control's ready event handler, add the following to the 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 RouteURL object
    var routeURL = new atlas.service.RouteURL(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. routeURL 表示 Azure Maps Route 操作的 URL。The routeURL represents a URL to Azure Maps Route operations.

  2. 在设置凭据和 URL 以后,请添加以下 JavaScript 代码,以便构建从起点到终点的卡车路线。After setting up credentials and the URL, add the following JavaScript code to construct a truck route route from start to end point. 此路线是为装载 USHazmatClass2 类货物的卡车创建和显示的。This route is created and displayed for a truck carrying USHazmatClass2 classed cargo.

    //Start and end point input to the routeURL
    var coordinates= [[startPoint.geometry.coordinates[0], startPoint.geometry.coordinates[1]], [endPoint.geometry.coordinates[0], endPoint.geometry.coordinates[1]]];
    
    //Make a search route request for a truck vehicle type
    routeURL.calculateRouteDirections(atlas.service.Aborter.timeout(10000), coordinates,{
        travelMode: 'truck',
        vehicleWidth: 2,
        vehicleHeight: 2,
        vehicleLength: 5,
        vehicleLoadType: 'USHazmatClass2'
    }).then((directions) => {
        //Get data features from response
        var data = directions.geojson.getFeatures();
    
        //Get the route line and add some style properties to it.  
        var routeLine = data.features[0];
        routeLine.properties.strokeColor = '#2272B9';
        routeLine.properties.strokeWidth = 9;
    
        //Add the route line to the data source. We want this to render below the car route which will likely be added to the data source faster, so insert it at index 0.
        datasource.add(routeLine, 0);
    });
    

    上述代码通过 Azure Maps 路线走向 API 查询 Azure Maps 路线服务。The code above queries the Azure Maps Route service through the Azure Maps Route Directions API. 然后,从使用 geojson.getFeatures() 方法提取的响应中的 GeoJSON 特征集合提取路线。The route line is then extracted from the GeoJSON feature collection from the response that is extracted using the geojson.getFeatures() method. 最后,该路线将添加到数据源。Finally, the route line is added to the data source. 我们要将它添加到索引 0 处,以确保先于数据源中的任何其他路线之前呈现卡车路线,因为卡车路线计算速度通常比小汽车路线计算速度慢。We are adding it at the index of 0, to ensure that the truck route is rendered before any other lines in the data source, because the truck route calculation will often be slower than a car route calculation. 如果先将小汽车路线添加到数据源,再次卡车路线添加到数据源,则会在小汽车路线的上面呈现卡车路线。If the truck route line is added to the data source after the car route, it will render above it. 将会向卡车路线添加两个属性:一个是蓝色的描边色,另一个是九像素的描边宽度。Two properties are added to the truck route line: a blue stroke color, and a stroke width of nine pixels.

    提示

    要查看 Azure Maps 路线走向 API 的所有可能的选项和值,请参阅 Post 路线走向的 URI 参数To see all possible options and values for the Azure Maps Route Directions API, see URI Parameters for Post Route Directions.

  3. 现在追加以下 JavaScript 代码,以构造小汽车路线。Now append the following JavaScript code to construct a route for a car.

    routeURL.calculateRouteDirections(atlas.service.Aborter.timeout(10000), coordinates).then((directions) => {
    
        //Get data features from response
        var data = directions.geojson.getFeatures();
    
        //Get the route line and add some style properties to it.  
        var routeLine = data.features[0];
        routeLine.properties.strokeColor = '#B76DAB';
        routeLine.properties.strokeWidth = 5;
    
        //Add the route line to the data source. This will add the car route after the truck route.  
        datasource.add(routeLine);
    });
    

    上述代码通过 Azure Maps 路线走向 API 方法来查询 Azure Maps 路线服务。The code above queries the Azure Maps routing service through the Azure Maps Route Directions API method. 然后,从使用 geojson.getFeatures() 方法提取的响应中的 GeoJSON 特征集合提取路线。The route line is then extracted from the GeoJSON feature collection from the response that is extracted using the geojson.getFeatures() method. 最后,该路线将添加到数据源。Finally, the route line is added to the data source. 将会向卡车路线添加两个属性:一个是紫色的描边色,另一个是五像素的描边宽度。Two properties are added to the truck route line: a purple stroke color, and a stroke width of five pixels.

  4. 保存 TruckRoute.html 文件并刷新 web 浏览器。Save the TruckRoute.html file and refresh your web browser. 地图现在应显示卡车路线和小汽车路线。The map should now display the truck and car routes.

    使用 Azure 路线服务的地图上的私家车和商用车路线

    卡车路线使用蓝色粗线显示。The truck route is displayed using a thick blue line. 小汽车路线使用紫色细线显示。The car route is displayed using a thin purple line. 小汽车路线经 I-90 穿过华盛顿湖,会经过居民区下的隧道。The car route goes across Lake Washington via I-90, passing through tunnels beneath residential areas. 由于隧道靠近居住区,因此会限制危险货物。Because the tunnels are close to residential areas, hazardous waste cargo is restricted. 卡车路线(指定 USHazmatClass2 货物类型)指向不同的公路。The truck route, which specifies a USHazmatClass2 cargo type, is directed to use a different highway.

可在此处获得示例的完整源代码。You can obtain the full source code for the sample here. 可在此处找到实时示例。A live sample can be found here.

还可以使用数据驱动的样式表达式You can also Use data-driven style expressions

清理资源Clean up resources

没有需要清理的资源。There are no resources that require cleanup.

后续步骤Next steps

下一教程演示使用 Azure Maps 创建简单商店定位器的过程。The next tutorial demonstrates the process of creating a simple store locator by using Azure Maps.