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")

The above code is copied from https://rstudio.github.io/leaflet/choropleths.html.

I am trying to reproduce the output. However, I got stuck in the first step - downloading the geojson file. I used the link shown in the first line, and save it as a text file and then rename it as a geojson file. But I failed to read that file. Obviously something wrong with file download or loading to R, but I have no idea where it is.

Can someone give any instructions? I have never deal with geojson data before. I just need help with the first two lines of codes, and I can handle all the others by myself.

1 Answer 1

4

The download file has a javascript assignment at the head. Removing it seems to fix the issue ,

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")
1
  • Thank you! This makes everything reproducible.
    – Bin
    Commented Apr 17, 2017 at 1:56

Not the answer you're looking for? Browse other questions tagged or ask your own question.