2012-08-15 144 views
0

我已經通過google api服務計算了城市之間的距離。 我需要的距離成中的R的距離矩陣,但是當我使用的代碼:google api距離矩陣轉換爲R

de1 <- "http://maps.googleapis.com/maps/api/distancematrix/json?origins=Berlin|Hamburg|Muenchen|Koeln|Frankfurt am Mein|Duesseldorf|Bremen|Hannover|Nuernberg&destinations=Berlin|Hamburg|Muenchen|Koeln|Frankfurt am Mein|Duesseldorf|Bremen|Hannover|Nuernberg&mode=driving&language=en&sensor=false" 
webpage1 <- getURL(de1) 
webpage1 <- readLines(tc <- textConnection(webpage1)); close(tc) 
pagetree <- htmlTreeParse(webpage1, error=function(...){}) 

如果我然後輸入「pagetree」我得到一個錯誤信息。

> pagetree 
<!DOCTYPE html> 
<html lang="en"> 
<head> 
<meta charset="utf-8"> 
<meta name="viewport" content="initial-scale=1, minimum-scale=1, width=device-width"> 
<title>Error 400 (Bad Request)!!1</title> 
<style> 
*{margin:0;padding:0}html,code{font:15px/22px arial,sans-serif}html{background:#fff;color:#222;padding:15px}body{margin:7% auto 0;max-width:390px;min-height:180px;padding:30px 0 15px}* > body{background:url(//www.google.com/images/errors/robot.png) 100% 5px no-repeat;padding-right:205px}p{margin:11px 0 22px;overflow:hidden}ins{color:#777;text-decoration:none}a img{border:0}@media screen and (max-width:772px){body{background:none;margin-top:0;max-width:none;padding-right:0}} 
</style> 
<a href="//www.google.com/"><img src="//www.google.com/images/errors/logo_sm.gif" alt="Google"></a> 
</head> 
<body> 
<p><b>400.</b> <ins>That&acirc;&#128;&#153;s an error.</ins> 
</p> 
<p>Your client has issued a malformed or illegal request. <ins>That&acirc;&#128;&#153;s all we know.</ins></p> 
</body> 
</html> 

有人可以幫我嗎?

謝謝, sofia p。

+0

你甚至都不需要'getURL'這裏,只是嘗試'readlines方法(用urlencode(DE 1))' – daroczig 2012-08-15 11:50:05

回答

2

嘗試

require(RCurl) 
webpage1 <- getURL(URLencode(de1)) 

也返回的數據爲JSON格式

require(RJSONIO) 
data<-fromJSON(webpage1) 

也許有用

,如果你想xml返回嘗試

require(XML) 
de2 <- "http://maps.googleapis.com/maps/api/distancematrix/xml?origins=Berlin|Hamburg|Muenchen|Koeln|Frankfurt am Mein|Duesseldorf|Bremen|Hannover|Nuernberg&destinations=Berlin|Hamburg|Muenchen|Koeln|Frankfurt am Mein|Duesseldorf|Bremen|Hannover|Nuernberg&mode=driving&language=en&sensor=false" 
webpage2 <- getURL(URLencode(de2)) 
data2<-xmlParse(webpage2) 
+0

謝謝!我只是一個初學者,我需要抒發你發給我的劇本,但這絕對有用。再次感謝! – 2013-04-12 12:58:48

0

試包ggmap

library(ggmap) 
mapdist(from, to, mode = c("driving", "walking", "bicycling"), 
output = c("simple", "all"), messaging = FALSE, sensor = FALSE, 
language = "en-EN", override_limit = FALSE)