4

次の関数を使用して、平均速度を 65 km/h と仮定して、特定の距離を運転するのにかかる時間 (時間単位) を推定します。

distHoras <- function(origin, destination){
  xml.url <- paste0('http://maps.googleapis.com/maps/api/distancematrix/xml?origins=',
                    origin, '&destinations=', destination, '&mode=driving&sensor=false')
  xmlfile <- xmlParse(getURL(xml.url))
  dist <- xmlValue(xmlChildren(xpathApply(xmlfile,"//distance")[[1]])$value)
  distance <- as.numeric(sub(" km", "", dist))
  time <- (distance / 1000) / 65
  return(time)
}

この関数を微調整して時間を直接取得するにはどうすればよいのでしょうか?この 65 km/h の仮定を行う必要がなく、より良い推定値を得ることができますか? ドキュメントを読んだ後、「距離」を「期間」に切り替えてみましたが、うまくいきませんでした。おそらく単純なものが欠けているのでしょうが、私は API を扱うのはまったく初めてで、そのすべてのテキストに圧倒されています。どんな助けにも感謝します!

4

2 に答える 2

5

あなたはこれを探していますか:

library(ggmap)
from <- 'Paris'
to <- 'London'
mapdist(from,to,mode='driving')
 from     to      m      km    miles seconds  minutes    hours
1 Paris London 454416 454.416 282.3741   18283 304.7167 5.078611

mapdistGoogle Mapsを使用してマップ距離を計算します。

あなたの質問に答えるには、XML よりも JSON バージョンの Google API を使用する方が簡単だと思います (推奨されます)。

ここでは、 を使用した高速バージョンRJSONIOです。上記の機能を使用することをお勧めします。結果はすでに時間単位であるため、変換を行う必要はありません。

library(RJSONIO)
distHoras <- function(origin, destinations){

origin <- gsub(",", "", origin)
origin <- gsub(" ", "+", origin)
origin <- paste("origins=", origin, sep = "")

destinations <- gsub(",", "", destinations)
destinations <- gsub(" ", "+", destinations)
destinations <- paste("destinations=", paste(destinations, 
                                             collapse = "|"), sep = "")


mode4url <- paste("mode=", 'driving', sep = "")
lang4url <- paste("language=", 'en-EN', sep = "")
sensor4url <- paste("sensor=", tolower(as.character(FALSE)), 
                   sep = "")
posturl <- paste(origin, destinations, mode4url, sensor4url, 
                 sep = "&")
url_string <- paste("http://maps.googleapis.com/maps/api/distancematrix/json?", 
                    posturl, sep = "")
url_string <- URLencode(url_string)
connect <- url(url_string)
tree <- fromJSON(paste(readLines(connect), collapse = ""))
close(connect)
rapply(tree$rows,I)
}

今、あなたはそれをテストします:

distHoras('Paris','London')
 elements.distance.text elements.distance.value  elements.duration.text 
               "454 km"                "454416"        "5 hours 5 mins" 
elements.duration.value         elements.status 
                "18283"                    "OK" 
于 2013-06-24T18:17:07.277 に答える