You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

如何基于Azure Maps Traffic Flow Segment返回坐标显示LineLayer?

解决方案:Azure Maps 交通流段数据加载与动画实现

核心结论

处理 /traffic/flow/segment 接口返回的 FlowSegmentData 数据时,不要用 VectorTileSource,而是使用 atlas.source.DataSource —— 它专门用于加载和管理GeoJSON格式的地理数据,完美匹配该接口返回的线段坐标结构。

分步实现代码

1. 初始化数据源与地图

先创建数据源并挂载到地图上:

// 初始化地图(假设已完成基础配置,替换为你的密钥)
const map = new atlas.Map('map', {
    authOptions: {
        authType: 'subscriptionKey',
        subscriptionKey: '你的Azure Maps密钥'
    }
});

// 创建用于存储交通流段的数据源
const segmentDataSource = new atlas.source.DataSource();
map.sources.add(segmentDataSource);

2. 请求并加载交通流段数据

调用 /traffic/flow/segment 接口,将返回的坐标转为GeoJSON格式后添加到数据源:

// 示例:请求指定经纬度附近的交通流段数据
fetch('https://atlas.microsoft.com/traffic/flow/segment/json?api-version=1.0&subscription-key=你的Azure Maps密钥&query=47.6062,-122.3321')
    .then(res => res.json())
    .then(data => {
        if (!data.flowSegments || data.flowSegments.length === 0) return;
        
        // 把每个交通流段转为GeoJSON LineFeature
        const lineFeatures = data.flowSegments.map(seg => {
            return new atlas.data.Feature(
                new atlas.data.LineString(seg.coordinates),
                {
                    // 携带交通流属性,用于后续样式控制
                    speed: seg.currentSpeed,
                    congestion: seg.congestionLevel
                }
            );
        });
        
        // 将数据批量添加到数据源
        segmentDataSource.add(lineFeatures);
    });

3. 创建带动画的LineLayer

通过配置虚线样式和动画属性,实现车流流动效果:

// 创建交通流线路图层
const flowLineLayer = new atlas.layer.LineLayer(segmentDataSource, null, {
    // 根据拥堵等级动态设置线条颜色
    strokeColor: [
        'interpolate',
        ['linear'],
        ['get', 'congestion'],
        0, '#2ecc71', // 畅通
        1, '#f39c12', // 缓行
        2, '#e74c3c', // 拥堵
        3, '#c0392b'  // 严重拥堵
    ],
    strokeWidth: 4,
    // 定义虚线样式:[实线长度, 空白长度]
    lineDashPattern: [0, 10],
    // 启用虚线滚动动画
    animate: true,
    // 动画周期(毫秒),值越小流动速度越快
    animationDuration: 2000
});

// 将图层添加到地图
map.layers.add(flowLineLayer);

关键细节

  • FlowSegmentData 的 coordinates 字段是经纬度数组,可直接用于构建GeoJSON LineString。
  • 动画本质是让虚线沿线路方向滚动,通过调整 lineDashPattern 的数值和 animationDuration 可以控制流动的视觉效果。
  • 利用返回的拥堵等级、实时速度等属性,可以实现更丰富的样式区分,提升可视化直观性。

内容的提问来源于stack exchange,提问作者HiDefLoLife

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.08.13 21:45:36