gpt4 book ai didi

r - ggmap 路线查找 - 不停留在道路上

转载 作者:行者123 更新时间:2023-12-04 01:59:03 28 4
gpt4 key购买 nike

我正在尝试使用 ggmap 中的 route() 函数映射路线。我的问题是路线不会停留在道路上。有什么东西是我的 route_df <- route(origin, destination, structure = "route")代码不见了?或者是否有替代功能可用于完成此操作?

示例代码:

install_github("rstudio/leaflet")
library(ggmap)
library(leaflet)
way1txt <- "Tinsletown, Vancouver, BC"
way2txt <- "Science World, Vancouver, BC"
route_df <- route(way1txt, way2txt, structure = "route")

# Map using Leaflet R
m = leaflet() %>% addTiles()
m = m %>% addPolylines(route_df$lon, route_df$lat, fill = FALSE)
m = m %>% addPopups(route_df$lon[1], route_df$lat[1], 'Origin')
m = m %>% addPopups(route_df$lon[length(route_df$lon)],
route_df$lat[length(route_df$lon)], 'Destination')
m

map 截图:

Screenshot of map with wrong route

最佳答案

看起来您实际上并未从 route() 获得所需的折线因为默认 output=参数设置为 simple .您可能需要将其更改为 all如下并开始解码折线。

以下是一种基于 decodeLine() 的解决方案取自 here 的函数.他们的解决方案是定义一个自定义函数来解码折线,然后绘制它解码的所有内容。

library(ggmap)
library(leaflet)
way1txt <- "Tinsletown, Vancouver, BC"
way2txt <- "Science World, Vancouver, BC"

route_all <- route(way1txt, way2txt, structure = "route",
output = "all")

# Custom decode function
# Taken from http://s4rdd.blogspot.com/2012/12/google-maps-api-decoding-polylines-for.html

decodeLine <- function(encoded){
require(bitops)

vlen <- nchar(encoded)
vindex <- 0
varray <- NULL
vlat <- 0
vlng <- 0

while(vindex < vlen){
vb <- NULL
vshift <- 0
vresult <- 0
repeat{
if(vindex + 1 <= vlen){
vindex <- vindex + 1
vb <- as.integer(charToRaw(substr(encoded, vindex, vindex))) - 63
}

vresult <- bitOr(vresult, bitShiftL(bitAnd(vb, 31), vshift))
vshift <- vshift + 5
if(vb < 32) break
}

dlat <- ifelse(
bitAnd(vresult, 1)
, -(bitShiftR(vresult, 1)+1)
, bitShiftR(vresult, 1)
)
vlat <- vlat + dlat

vshift <- 0
vresult <- 0
repeat{
if(vindex + 1 <= vlen) {
vindex <- vindex+1
vb <- as.integer(charToRaw(substr(encoded, vindex, vindex))) - 63
}

vresult <- bitOr(vresult, bitShiftL(bitAnd(vb, 31), vshift))
vshift <- vshift + 5
if(vb < 32) break
}

dlng <- ifelse(
bitAnd(vresult, 1)
, -(bitShiftR(vresult, 1)+1)
, bitShiftR(vresult, 1)
)
vlng <- vlng + dlng

varray <- rbind(varray, c(vlat * 1e-5, vlng * 1e-5))
}
coords <- data.frame(varray)
names(coords) <- c("lat", "lon")
coords
}


route_df <- decodeLine( route_all$routes[[1]]$overview_polyline$points )


# Map using Leaflet R
m = leaflet() %>% addTiles()
m = m %>% addPolylines(route_df$lon, route_df$lat, fill = FALSE)
m = m %>% addPopups(route_df$lon[1], route_df$lat[1], 'Origin')
m = m %>% addPopups(route_df$lon[length(route_df$lon)],
route_df$lat[length(route_df$lon)], 'Destination')
m

我明白了:

enter image description here

作为引用,还有一个 decodeLine功能 here由@diegovalle 撰写。

关于r - ggmap 路线查找 - 不停留在道路上,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/30270011/

28 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com