首页
学习
活动
专区
圈层
工具
发布
社区首页 >问答首页 >在rMaps/rCharts中使用传单路由机的路径总距离

在rMaps/rCharts中使用传单路由机的路径总距离
EN

Stack Overflow用户
提问于 2015-04-14 17:30:28
回答 1查看 1.5K关注 0票数 0

我想生产一个闪亮的应用程序,要求两个地址,映射一个有效的路线,并计算路线的总距离。这可以使用使用javascript库的传单选路机来完成,但是我想用路由的距离做一些进一步的计算,并将其全部嵌入到一个闪亮的应用程序中。

通过遵循Ramnathv 这里的演示,您可以使用rMaps生成地图。但是我无法计算出旅行的总距离,即使我可以看到它是在传说或控制器中计算出来的。关于如何使用javascript库进行此操作,还有另一个讨论--参见这里。他们讨论使用这个javascript代码:

代码语言:javascript
复制
alert('Distance: ' + routes[0].summary.totalDistance);

这是我的rMap工作代码。如果有人想出一条路线的总距离并储存它,我将非常感激。谢谢!

代码语言:javascript
复制
# INSTALL DEPENDENCIES IF YOU HAVEN'T ALREADY DONE SO
library(devtools)
install_github("ramnathv/rCharts@dev")
install_github("ramnathv/rMaps")

# CREATE FUNCTION to convert address to coordinates
library(RCurl)
library(RJSONIO)

construct.geocode.url <- function(address, return.call = "json", sensor = "false") {
  root <- "http://maps.google.com/maps/api/geocode/"
  u <- paste(root, return.call, "?address=", address, "&sensor=", sensor, sep = "")
  return(URLencode(u))
}

gGeoCode <- function(address,verbose=FALSE) {
  if(verbose) cat(address,"\n")
  u <- construct.geocode.url(address)
  doc <- getURL(u)
  x <- fromJSON(doc)
  if(x$status=="OK") {
    lat <- x$results[[1]]$geometry$location$lat
    lng <- x$results[[1]]$geometry$location$lng
    return(c(lat, lng))
  } else {
    return(c(NA,NA))
  }
}

# GET COORDINATES
x <- gGeoCode("Vancouver, BC")
way1 <- gGeoCode("645 East Hastings Street, Vancouver, BC")
way2 <- gGeoCode("2095 Commercial Drive, Vancouver, BC")

# PRODUCE MAP
library(rMaps)
map = Leaflet$new()
map$setView(c(x[1], x[2]), 16)
map$tileLayer(provider = 'Stamen.TonerLite')

mywaypoints = list(c(way1[1], way1[2]), c(way2[1], way2[2]))

map$addAssets(
  css = "http://www.liedman.net/leaflet-routing-machine/dist/leaflet-routing-machine.css",
  jshead = "http://www.liedman.net/leaflet-routing-machine/dist/leaflet-routing-machine.js"
)

routingTemplate = "
 <script>
 var mywaypoints = %s
 L.Routing.control({
  waypoints: [
    L.latLng.apply(null, mywaypoints[0]),
    L.latLng.apply(null, mywaypoints[1])
  ]
 }).addTo(map);
 </script>"

map$setTemplate(
  afterScript = sprintf(routingTemplate, RJSONIO::toJSON(mywaypoints))
)
# map$set(width = 800, height = 800)
map
EN

回答 1

Stack Overflow用户

回答已采纳

发布于 2015-04-17 20:36:26

您可以通过轻松地创建一条路由。返回的数据帧将有距离信息。把腿的总距离加起来。

代码语言:javascript
复制
library(ggmap)
x <- gGeoCode("Vancouver, BC")
way1txt <- "645 East Hastings Street, Vancouver, BC"
way2txt <- "2095 Commercial Drive, Vancouver, BC"
route_df <- route(way1txt, way2txt, structure = 'route')
dist<-sum(route_df[,1],na.rm=T) # total distance in meters
#
qmap(c(x[2],x[1]), zoom = 12) +
   geom_path(aes(x = lon, y = lat),  colour = 'red', size = 1.5, data = route_df, lineend = 'round') 
票数 1
EN
页面原文内容由Stack Overflow提供。腾讯云小微IT领域专用引擎提供翻译支持
原文链接:

https://stackoverflow.com/questions/29633797

复制
相关文章

相似问题

领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档