楚新元 | All in R

Welcome to R Square

用 R 调用高德地图实现路径规划

楚新元 / 2021-10-14


实现该功能需要先去高德开放平台注册后,创建应用添加key,然后在R工作目录下创建一个 .Renviron 文件,文件内容为 key = 'YOUR AMAP KEY'

加载相关 R 包

library(httr)
library(dplyr)
library(purrr)
library(tidyr)
library(jsonlite)
library(tidytext)
library(stringr)
library(sf)
library(leaflet)
library(leafletCN)
library(leafem)

编写生成导航地图的函数

必要的参数:起点、终点和出行方式。输出结果包含路线距离、预计耗时及路线图。

navigation = function(start_point, end_point, by = "driving") {
  
  # by = "walking"     表示步行
  # by = "transit"     表示公交
  # by = "driving"     表示驾车
  # by = "bicycling"   表示骑行
  
  # 定义一个高德API Key
  key = Sys.getenv("key")
  
  # 生成一个关于起点和终点的向量
  address = c(
    start = start_point, 
    end = end_point
  )
  
  # 编写函数获取给定地点的经纬度坐标数据
  coordinate = \(address) {
    url = paste0(
      'https://restapi.amap.com/v3/geocode/geo?key=', key,
      '&address=', address
    )
    url %>% 
      GET() %>% 
      content(as = "text") %>% 
      fromJSON() %>% 
      magrittr::extract2("geocodes") %>%
      bind_rows() %>%
      select(formatted_address, location)
  }
  
  # 获取起点和终点经纬度坐标数据
  address %>%
    map(coordinate) %>%
    list_rbind(names_to = "type") -> df
  origin = df$location[df$type == "start"]
  destination = df$location[df$type == "end"]

  # 生成一个关于起点和终点的地址
  url_start_end = paste0(
    "https://restapi.amap.com/v3/direction/", by, 
    "?origin=", origin, 
    "&destination=", destination, 
    "&key=", key
  )
  
  # 解析地址并返回路程、耗时和关键点经纬度
  url_start_end %>%
    GET() %>% 
    content(as = "text") %>% 
    fromJSON() -> routelist
  
  # 输出距离和耗时信息
  dist = routelist$route$paths$distance  # 距离(单位:米)
  duration = routelist$route$paths$duration  # 耗时(单位:秒)
  meta = data.frame(
    dist = round(as.numeric(dist) / 1000, 2),
    duration = round(as.numeric(duration) / 60, 0)
  )
  colnames(meta) = c("路线距离(千米)", "预计耗时(分钟)")
  print(meta)
  
  # 生成途经关键点串联坐标
  routelist$route$paths$steps %>%
    bind_rows() %>% 
    select(polyline) %>% 
    unnest_tokens(
      polyline, polyline,
      token = str_split,
      pattern = ";"
    ) %>% 
    separate(
      polyline, into = c("lon", "lat"), sep = ","
    ) %>% 
    mutate(across(c(lon, lat), as.double)) %>% 
    as.matrix() %>% 
    st_linestring() -> path
  
  # 生成高德导航地图
  leaflet(width = "100%", height = "400px") %>%  
    amap() %>% 
    addFeatures(data = path, color = "red", weight = 10) 

}

实战测试

# 驾驶模式
navigation("西安市人民政府", "杭州市人民政府", by = "driving")
#>   路线距离(千米) 预计耗时(分钟)
#> 1           1343.2              853