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

教程:如何使用 Azure Maps 路线服务和地图控件显示路线走向

本教程演示如何使用 Azure Maps 路线服务 API地图控件显示从起点到终点的路线走向。 本教程演示如何:

  • 在网页上创建和显示地图控件。
  • 通过定义符号层线条层来定义路线的显示呈现。
  • 创建 GeoJSON 对象并将其添加到地图,以表示起点和终点。
  • 使用获取路线走向 API 获取从起点到终点的路线走向。

有关源代码,请参阅 GitHub 中的路线教程。 有关实时示例,请参阅通往目的地的路线

先决条件

创建和显示地图控件

以下步骤演示如何在网页中创建和显示地图控件。

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

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

    <!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/3/atlas.min.css" type="text/css">
        <script src="https://atlas.microsoft.com/sdk/javascript/mapcontrol/3/atlas.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 的一些信息:

    • HTML 标头包含 Azure Map Control 库托管的 CSS 和 JavaScript 资源文件。
    • 当页面正文加载时,页面正文中的 onload 事件会调用 GetMap 函数。
    • GetMap 函数包含用于访问 Azure Maps API 的内联 JavaScript 代码。 下一步将添加它。
  3. 接下来,将以下 JavaScript 代码添加到 GetMap 函数,位于最后一步中添加的代码正下方。 此代码将创建一个地图控件,然后使用你提供的 Azure Maps 订阅密钥对其进行初始化。 确保将字符串 <Your Azure Maps Key> 替换为从 Maps 帐户复制的 Azure Maps 主密钥。

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

    需要了解的有关上述 JavaScript 的一些信息:

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

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

定义路线显示呈现

在本教程中,将使用线条层呈现路线。 起点和终点使用符号层进行呈现。 有关添加线条层的详细信息,请参阅将线条层添加到地图。 若要了解有关符号层的详细信息,请参阅将符号层添加到地图

  1. 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 the route lines and have it render under the map labels.
        map.layers.add(new atlas.layer.LineLayer(datasource, null, {
            strokeColor: '#2272B9',
            strokeWidth: 5,
            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.
        }));
    });
    

    需要了解的有关上述 JavaScript 的一些信息:

    • 此代码实现地图控件的 ready 事件处理程序。 本教程中的其余代码在 ready 事件处理程序中。
    • 在地图控件的 ready 事件处理程序中,将会创建一个数据源来存储从起点到终点的路线。
    • 为了定义路线的呈现方式,将会创建一个线条层并将其附加到数据源。 为了确保路线不遮盖道路标签,可以提供第二个参数,其值为 'labels'

    接下来,将会创建一个符号层并将其附加到数据源。 此层指定起点和终点的呈现方式。 添加了表达式以从每个点对象的属性中检索图标图像和文本标签信息。 若要详细了解表达式,请参阅数据驱动的样式表达式

  2. 接下来,将起点设为 Microsoft,将终点设为西雅图的一个加油站。 通过在地图控件的 ready 事件处理程序中追加以下代码来创建起点和终点:

    //Create the GeoJSON objects which represent the start and end points of the route.
    var startPoint = new atlas.data.Feature(new atlas.data.Point([-122.130137, 47.644702]), {
        title: "Redmond",
        icon: "pin-blue"
    });
    
    var endPoint = new atlas.data.Feature(new atlas.data.Point([-122.3352, 47.61397]), {
        title: "Seattle",
        icon: "pin-round-blue"
    });
    
    //Add the data to the data source.
    datasource.add([startPoint, endPoint]);
    
    map.setCamera({
        bounds: atlas.data.BoundingBox.fromData([startPoint, endPoint]),
        padding: 80
    });
    

    需要了解的有关上述 JavaScript 的一些信息:

    • 此代码创建两个 GeoJSON 点对象来表示起点和终点,这两个对象随后添加到数据源中。
    • 最后一个代码块使用起点和终点的纬度和经度来设置相机视图。
    • 起点和终点会添加到数据源。
    • 起点和终点的边框使用 atlas.data.BoundingBox.fromData 函数计算。 此边框用于通过 map.setCamera 函数设置基于整个路线的地图相机视图。
    • 将会添加一个填充来弥补符号图标的像素尺寸。

    有关地图控件的 setCamera 属性的详细信息,请参阅 setCamera(CameraOptions | CameraBoundsOptions & AnimationOptions) 属性。

  3. 保存 MapRoute.html 并刷新浏览器。 现在,地图以西雅图为中心。 蓝色泪珠形图钉标记起点。 蓝色圆形图钉标记终点。

    地图的屏幕截图,地图上的一个路线包含一个蓝色泪珠大头针(标记了位于华盛顿雷德蒙德的 Microsoft 作为起点)和一个蓝色圆形大头针(标记了位于西雅图的一个加油站作为终点)。

获取路线走向

本部分演示如何使用 Azure Maps 路线走向 API 来获取路线走向以及从一个点到另一个点的预计到达时间。

提示

Azure Maps 路线服务提供 API 来根据不同的路线类型规划路线,例如根据距离、路况和所用交通方式提供最快路线、最短路线、生态路线或惊险路线 。 此服务还让用户可以根据历史路况规划将来的路线。 用户可以看到任何给定时间的路线时间预测。 有关详细信息,请参阅获取路线走向 API

  1. GetMap 函数的控件的 ready 事件处理程序中,将以下内容添加到 JavaScript 代码中。

    var query = startPoint.geometry.coordinates[1] + "," +
                startPoint.geometry.coordinates[0] + ":" +
                endPoint.geometry.coordinates[1] + "," +
                endPoint.geometry.coordinates[0];
    var url = `https://atlas.microsoft.com/route/directions/json?api-version=1.0&query=${query}`;
    
    //Make a search route request
    fetch(url, {
        headers: {
            "Subscription-Key": map.authentication.getToken()
        }
    })
    .then((response) => response.json())
    .then((response) => {
        var route = response.routes[0];
        //Create an array to store the coordinates of each turn
        var routeCoordinates = [];
        route.legs.forEach((leg) => {
            var legCoordinates = leg.points.map((point) => {
                return [point.longitude, point.latitude];
            });
            //Add each turn to the array
            routeCoordinates = routeCoordinates.concat(legCoordinates);
        });
        //Add route line to the datasource
        datasource.add(new atlas.data.Feature(new atlas.data.LineString(routeCoordinates)));
    });
    

    需要了解的有关上述 JavaScript 的一些信息:

    • 此代码构造从起点到终点的路线。
    • url 会查询 Azure Maps 路线服务 API 来计算路线走向。
    • 然后,从响应中提取坐标数组,并将其添加到数据源。
  2. 保存“MapRoute.html”文件并刷新 web 浏览器。 现在,地图应显示从起点到终点的路线。

    在地图上演示 Azure 地图控件和路线服务的屏幕截图。

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

后续步骤

下一教程演示如何在有限制的情况下(例如出行模式或货物类型)创建路线查询。 你随后可以在同一地图上显示多条路线。