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

如何基于DataFrame绘制带时间维度的Folium.PolyLine(类似HeatMapWithTime)

实现带时间维度的Folium PolyLine(类似HeatMapWithTime效果)

可以借助folium.plugins.TimestampedGeoJson插件来实现时间维度的轨迹展示,以下是完整的实现步骤和代码:

1. 数据预处理

首先将数据中的Datetime转为标准日期格式,按车辆分组并按时间排序轨迹点:

import pandas as pd
import folium
from folium.plugins import TimestampedGeoJson

# 加载你的数据(这里用示例数据)
data = {
    'Datetime': ['2021-06-01', '2021-06-01', '2021-06-01', '2021-06-02'],
    'Lat': [4.5, 4.8, 4.4, 4.7],
    'lon': [1.1, 0.8, 0.9, 1.0],
    'Cars': ['Car1', 'Car1', 'Car2', 'Car2']
}
df = pd.DataFrame(data)
df['Datetime'] = pd.to_datetime(df['Datetime'])

2. 构建时间序列GeoJSON要素

按车辆分组生成轨迹线段(LineString),并为每个线段绑定对应的时间戳:

features = []
for car, group in df.groupby('Cars'):
    # 按时间排序轨迹点
    sorted_group = group.sort_values('Datetime')
    coords = list(zip(sorted_group['Lat'], sorted_group['lon']))
    
    # 生成相邻点的轨迹线段
    for i in range(1, len(coords)):
        feature = {
            'type': 'Feature',
            'geometry': {
                'type': 'LineString',
                'coordinates': [coords[i-1], coords[i]]
            },
            'properties': {
                'time': sorted_group['Datetime'].iloc[i].isoformat(),
                'style': {'color': '#1f77b4' if car == 'Car1' else '#ff7f0e', 'weight': 4},
                'iconstyle': {'fillColor': '#1f77b4' if car == 'Car1' else '#ff7f0e', 'fillOpacity': 0.8}
            }
        }
        features.append(feature)
    
    # 处理只有单个点的情况(可选)
    if len(coords) == 1:
        feature = {
            'type': 'Feature',
            'geometry': {'type': 'Point', 'coordinates': coords[0]},
            'properties': {
                'time': sorted_group['Datetime'].iloc[0].isoformat(),
                'iconstyle': {'fillColor': '#1f77b4' if car == 'Car1' else '#ff7f0e', 'radius': 6}
            }
        }
        features.append(feature)

3. 生成带时间滑块的地图

使用TimestampedGeoJson加载要素,配置时间滑块参数:

# 地图中心设为数据的平均坐标
map_center = [df['Lat'].mean(), df['lon'].mean()]
m = folium.Map(location=map_center, zoom_start=10)

# 添加时间轨迹图层
TimestampedGeoJson(
    {'type': 'FeatureCollection', 'features': features},
    period='P1D',  # 时间间隔为1天
    auto_play=False,
    loop=False,
    date_options='YYYY-MM-DD',
    time_slider_drag_update=True,
    loop_button=True
).add_to(m)

# 保存地图
m.save('car_trajectory_time.html')

关键说明

  • 若要实现累积轨迹(滑动时间轴时展示截至当前时间的所有路径),可将properties中的time替换为times,设置轨迹的时间范围:
    'times': [sorted_group['Datetime'].iloc[0].isoformat(), sorted_group['Datetime'].iloc[i].isoformat()]
    
  • 可通过style参数自定义线段颜色、粗细,区分不同车辆
  • period参数控制时间滑块的间隔,P1D代表1天,PT1H代表1小时,可根据数据粒度调整

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.06.26 05:50:16