2017-04-16 85 views
4
# From http://leafletjs.com/examples/choropleth/us-states.js 
states <- geojsonio::geojson_read("json/us-states.geojson", what = "sp") 

bins <- c(0, 10, 20, 50, 100, 200, 500, 1000, Inf) 
pal <- colorBin("YlOrRd", domain = states$density, bins = bins) 

labels <- sprintf(
    "<strong>%s</strong><br/>%g people/mi<sup>2</sup>", 
    states$name, states$density 
) %>% lapply(htmltools::HTML) 

leaflet(states) %>% 
    setView(-96, 37.8, 4) %>% 
    addProviderTiles("MapBox", options = providerTileOptions(
    id = "mapbox.light", 
    accessToken = Sys.getenv('MAPBOX_ACCESS_TOKEN'))) %>% 
    addPolygons(
    fillColor = ~pal(density), 
    weight = 2, 
    opacity = 1, 
    color = "white", 
    dashArray = "3", 
    fillOpacity = 0.7, 
    highlight = highlightOptions(
     weight = 5, 
     color = "#666", 
     dashArray = "", 
     fillOpacity = 0.7, 
     bringToFront = TRUE), 
    label = labels, 
    labelOptions = labelOptions(
     style = list("font-weight" = "normal", padding = "3px 8px"), 
     textsize = "15px", 
     direction = "auto")) %>% 
    addLegend(pal = pal, values = ~density, opacity = 0.7, title = NULL, 
    position = "bottomright") 

上述代碼複製自https://rstudio.github.io/leaflet/choropleths.html如何下載geojson數據並將其讀取到R

我想重現輸出。但是,我陷入了第一步 - 下載geojson文件。我使用了第一行顯示的鏈接,並將其保存爲文本文件,然後將其重命名爲geojson文件。但是我沒有閱讀那個文件。很明顯,文件下載或加載到R有問題,但我不知道它在哪裏。

有人可以提供任何指示嗎?我從來沒有處理過geojson數據。我只需要前兩行代碼的幫助,我可以自己處理所有其他代碼。

回答

2

下載文件頭部有一個javascript分配。刪除它似乎解決了這個問題,

library(geojson) 
library(geojsonio) 
url <- "http://leafletjs.com/examples/choropleth/us-states.js" 

# read as text file 
doc <- readLines(url) 

# remove the javascript assignment at the front 
doc2 <- gsub("var statesData = ", "", doc) 

# write out as a temp file and read 
write(doc2, file = "tempgeo.json") 
states <- geojson_read("tempgeo.json", what = "sp") 
+0

謝謝!這使得一切都可以重現。 – Bin

相關問題