简体   繁体   中英

Unable to use GeoJSON using leaflet package in R

I am trying to plot the GeoJSON in R using Leaflet package. Below is the code and the error.

  library(geojsonio)
    library(leaflet)
    library(data.table)
    library(plyr)
    library(rgdal)
    library(sp)
    library(RColorBrewer)
    library(rgeos) #for simplification
    library(leafletR)
    library(sf)
    library(jsonlite)
    library(RJSONIO)

    mydata <- fromJSON("https://gist.githubusercontent.com/senthilthyagarajan/eb7a2771eab4639e94d5f9eaad28cb33/raw/1cfe355a56d2c1856a70a5389a4eadf06d782748/data.geojson",flatten=TRUE)


    leaflet(mydata) %>%
      addPolygons(color = "#444444", weight = 1, smoothFactor = 0.5,
                  opacity = 1.0, fillOpacity = 0.5,
                  fillColor = ~colorQuantile("YlOrRd", nghbrhd)(nghbrhd),
                  highlightOptions = highlightOptions(color = "white", weight = 2,
                                                      bringToFront = TRUE))


    Error: lexical error: invalid char in json text.
                                           FeatureCollection
                         (right here) ------^

Please ignore the long list of packages mentioned above.

Your data needs to be of "SpatialPolygonsDataFrame" type. When I run your code above, mydata is of type list which produces the error. I used geojson_read from geojsonio package to read the data (specifying the sp: spatialpolygons data type) and I get a leaflet plot. Flatten is not a parameter in geojson_read function but you can look into the parse argument to turn a geojson object in a dataframe if interested.

library(leaflet)
mydata <- geojsonio::geojson_read("https://gist.githubusercontent.com/senthilthyagarajan/eb7a2771eab4639e94d5f9eaad28cb33/raw/1cfe355a56d2c1856a70a5389a4eadf06d782748/data.geojson",what = "sp")

leaflet(mydata) %>%
  addPolygons(color = "#444444", weight = 1, smoothFactor = 0.5,
              opacity = 1.0, fillOpacity = 0.5,
              fillColor = ~colorQuantile("YlOrRd", nghbrhd)(nghbrhd),
              highlightOptions = highlightOptions(color = "white", weight = 2,
                                                  bringToFront = TRUE))

在此处输入图片说明

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM