Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Use strings of geoJSON with leaflet

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.

like image 510
user1923975 Avatar asked Oct 18 '22 15:10

user1923975


1 Answers

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)

enter image description here

like image 92
sckott Avatar answered Oct 20 '22 11:10

sckott