如何下载GeoJSON数据并将其读入R

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文件上。我使用了第一行中显示的链接,将其保存为文本文件,然后将其重命名为geojson文件。但是我无法读取该文件。很明显,在文件下载或加载到R时出现了问题,但我不知道问题出在哪里。
有人能给出任何指导吗?我以前从未处理过geojson数据。我只需要帮助处理前两行代码,其他部分我可以自己解决。
1个回答

4
下载文件在头部有一个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")

谢谢!这使得所有东西都可以再现。 - Bin

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接