2015-04-14 26 views
0

我想制作一个闪亮的应用程序,要求两个地址,映射一条有效路线,并计算路线的总距离。这可以使用使用JavaScript库的Leaflet Routing Machine完成,但是我想对路线的距离进行一些进一步的计算,并将它们全部嵌入到闪亮的应用程序中。在rMaps/rCharts中使用传单路由机的路由总距离

您可以按照Ramnathv here的演示,使用rMaps生成地图。但是,即使我可以看到它已经在图例或控制器中计算出来,但我仍无法提取总行程。还有一个关于如何使用JavaScript库来做到这一点的讨论 - 请参阅here。他们讨论使用此javascript代码:

alert('Distance: ' + routes[0].summary.totalDistance); 

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

# INSTALL DEPENDENCIES IF YOU HAVEN'T ALREADY DONE SO 
library(devtools) 
install_github("ramnathv/[email protected]") 
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 

回答

1

您可以通过google maps api轻松创建路线。返回的数据帧将有距离信息。总结总距离的腿。

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') 
+0

这太好了。谢谢!虽然,我希望我可以更多地与地图互动(例如,放大和缩小),并根据路线将地图位置放大并进行缩放。而且,qmap确实有点慢,这在使用Shiny打包时可能会有问题。但除此之外,这正是我所需要的。 – cnmillar

+0

我刚刚添加了qmap作为快速示例图。但是,它是有限的。您应该能够从route_df中获取坐标信息并在小册子地图上绘制类似的线条。 – jcplum

+0

这是一个好主意,re:以传单的形式呈现route_df和情节。谢谢! – cnmillar