2015-04-14 28 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