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

R语言合并多段路径实现带中途停留的车辆移动动画

实现方案

  • 多段行程合并:将A→B采样点、B点停留帧、B→A采样点按顺序拼接为统一序列,后续新增前往C点的行程只需在序列末尾追加对应路段的采样点即可,适配扩展需求。
  • 停留效果实现:在两段行程的衔接处插入若干重复的B点,重复次数根据停留时长计算:停留帧数 = 停留秒数 * 100 / delay参数值,tmap_animation的delay参数单位为1/100秒,比如delay=10时每帧间隔0.1秒,3秒停留对应插入30个重复B点。

修改后完整代码如下:

# load packages
library(sf)
library(dplyr)
library(tidygeocoder)
library(osrm)
library(tmap)
library(gifski)

# 1. 纽约世贸中心
# 2. 纽约麦迪逊广场公园
adresses <- c("285 Fulton St, New York, NY 10007", 
              "11 Madison Ave, New York, NY 10010")

# 地址转坐标并转换为sf数据结构
data <- tidygeocoder::geo(adresses, method = "osm") %>% 
  st_as_sf(coords = c("long", "lat"), crs = 4326)

# 路线1:A→B 世贸中心到麦迪逊广场
osroute_1 <- osrm::osrmRoute(loc = data, returnclass = "sf")
# 路线2:B→A 麦迪逊广场返回世贸中心
osroute_2 <- osrm::osrmRoute(loc = data %>% arrange(-row_number()), returnclass = "sf")
# 合并所有路线用于统一展示
all_routes <- rbind(osroute_1, osroute_2)

# 采样A→B路线点
osroute_sampled_1 <- st_sample(osroute_1, type = 'regular', size = 50) %>%
  st_cast('POINT') %>%
  st_as_sf() 
# 采样B→A路线点,去掉第一个点(和B点重复,避免冗余)
osroute_sampled_2 <- st_sample(osroute_2, type = 'regular', size = 50) %>%
  st_cast('POINT') %>%
  st_as_sf() %>%
  slice(-1)

# --------------------------
# 生成B点停留帧
# 停留3秒,delay=10对应30帧
stay_frames <- 30
point_b <- osroute_sampled_1[nrow(osroute_sampled_1), ]
stay_points <- do.call(rbind, replicate(stay_frames, point_b, simplify = FALSE))
# --------------------------

# 合并所有动画帧对应的点位:A→B + B点停留 + B→A
all_points <- rbind(osroute_sampled_1, stay_points, osroute_sampled_2)

# 一次性生成所有动画帧
animation_frames <- lapply(seq_along(1:nrow(all_points)), function(point){
  x <- all_points[point,]
  tm_shape(all_routes) +  # 展示完整往返路线
    tm_sf() +
    tm_shape(data) +      # 起终点标记
    tm_markers() +
    tm_shape(x) +         # 当前车辆位置
    tm_sf(col = 'red', size = 3)
})

# 渲染完整动画
tmap_animation(animation_frames, width = 300, height = 600, delay = 10)

如果后续需要新增从B点前往C点的行程,只需新增B→C的路线采样,直接追加到all_points序列末尾即可,无需修改现有逻辑。


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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.10.07 04:30:00