2016-05-31 59 views
1

我想從谷歌地圖API距離矩陣到R的數據。我想要得到JSON數據到R.如何將JSON數據下載到R,所以我可以稍後解析?JSON:Google Map中的距離矩陣數據「如何將JSON數據下載到R?」

require(rjson) 
url <- "https://maps.googleapis.com/maps/api/distancematrix/jsonunits=imperial&origins=19+East+34th+Street+NewYork+NY+10016&destinations=40.5177433,-74.2749576&mode=transit&language=fr-FR&key=API_KEY_HERE" 
raw.data <- readLines(url, warn = "F") 
rd <- fromJSON(raw.data) 

我收到此錯誤:

Error in fromJSON(raw.data) : unexpected character '<' 

感謝您的幫助

+0

你看過'httr'包嗎? – cory

回答

0

它只是恰巧我寫了一個包,googleway,可以幫助:

library(googleway) 

google_distance(origins = "19 East 34th Street NewYork NY 10016", 
       destinations = list(c(40.5177433,-74.2749576)), 
       key = key, 
       mode = "transit", 
       language = "fr") 

$destination_addresses 
[1] "350-356 Lawrie St, Perth Amboy, NJ 08861, États-Unis" 

$origin_addresses 
[1] "19 E 34th St, New York, NY 10016, États-Unis" 

$rows 
elements 
1 51,3 km, 51305, 1 heure 27 min, 5249, OK 

$status 
[1] "OK" 

同樣,設置simplify = FALSE得到原始JSON

google_distance(origins = "19 East 34th Street NewYork NY 10016", 
       destinations = list(c(40.5177433,-74.2749576)), 
       key = key, 
       mode = "transit", 
       language = "fr", 
       simplify = FALSE) 


[1] "{"                       
[2] " \"destination_addresses\" : [ \"350-356 Lawrie St, Perth Amboy, NJ 08861, États-Unis\" ]," 
[3] " \"origin_addresses\" : [ \"19 E 34th St, New York, NY 10016, États-Unis\" ],"    
[4] " \"rows\" : ["                    
[5] "  {"                      
[6] "   \"elements\" : ["                 
[7] "   {"                    
[8] "    \"distance\" : {"                
[9] "     \"text\" : \"51,3 km\","             
[10] "     \"value\" : 51305"               
[11] "    },"                   
[12] "    \"duration\" : {"                
[13] "     \"text\" : \"1 heure 27 min\","            
[14] "     \"value\" : 5249"               
[15] "    },"                   
[16] "    \"status\" : \"OK\""               
[17] "   }"                    
[18] "   ]"                     
[19] "  }"                      
[20] " ],"                      
[21] " \"status\" : \"OK\""                  
[22] "}" 

(其中simplify == TRUE使用jsonlite::fromJSON

0

我弄清楚如何通過JSONLite做到這一點。我正在使用R的本地「fromJSON」,這是造成問題的原因。

rd <-jsonlite::fromJSON("Google_API_CALL_IN_HERE", simplifyDataFrame = TRUE)