I have a dataframe where my first columns is geojson strings and the second is a metric for that location. The string in the first column renders properly if pasted into https://geojson.io/
I want to plot this with leaflet within R, as shown in the following link. https://rstudio.github.io/leaflet/json.html
Unfortunately, I don't know how to get my data into a format that will work with leaflet (seemingly an sp object).
Example row of data:
geojson <- '{"type": "Polygon", "coordinates": [[ [-104.05, 48.99], [-97.22, 48.98], [-96.58, 45.94], [-104.03, 45.94], [-104.05, 48.99] ]]}'
measure1 <- 10000
test_df <- data.frame(geojson, measure1)
test_df$geojson <- as.character(test_df$geojson)
Any other tips on best practices in a situation like this would also be appreciated.
Pretty sure leaflet
requires that the geojson have a properties
slot. You can do that with geojson
pkg, e.g.,
library(leaflet)
library(geojson)
geojson <- '{"type": "Polygon", "coordinates": [[ [-104.05, 48.99], [-97.22, 48.98], [-96.58, 45.94], [-104.03, 45.94], [-104.05, 48.99] ]]}'
geojson <- geojson::properties_add(geojson, population = 10000)
You can of course add the properties slot manually manipulating the string, but we use jqr
, a fast JSON parser that will make sure to do it right
measure1 <- 10000
df <- data.frame(geojson, measure1, stringsAsFactors = FALSE)
leaflet() %>%
addTiles() %>%
addGeoJSON(df$geojson) %>%
setView(-100, 47.6, 7)
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With