Reputation: 1389
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.
Upvotes: 5
Views: 903
Reputation: 26258
You can use library(geojsonsf)
to convert the geojson column to an sfc
column (and from then create an sf
object)
## construct data (I've added an extra row)
geojson <- c('{"type": "Polygon", "coordinates": [[ [-104.05, 48.99], [-97.22, 48.98], [-96.58, 45.94], [-104.03, 45.94], [-104.05, 48.99] ]]}',
'{"type": "Polygon", "coordinates": [[ [-103.05, 47.99], [-96.22, 47.98], [-93.58, 41.94], [-104.03, 45.94], [-103.05, 47.99] ]]}')
measure1 <- c(10000,20000)
test_df <- data.frame(geojson, measure1)
test_df$geojson <- as.character(test_df$geojson)
## create an 'sfc' column
test_df$geojson <- geojsonsf::geojson_sfc(test_df$geojson)
Use library(sf)
to make it into an sf
object
library(sf)
sf <- sf::st_sf(test_df)
sf
# Simple feature collection with 2 features and 1 field
# geometry type: POLYGON
# dimension: XY
# bbox: xmin: -104.05 ymin: 41.94 xmax: -93.58 ymax: 48.99
# epsg (SRID): 4326
# proj4string: +proj=longlat +datum=WGS84 +no_defs
# measure1 geojson
# 1 10000 POLYGON ((-104.05 48.99, -9...
# 2 20000 POLYGON ((-103.05 47.99, -9...
Here you can do whatever you want with this sf
object.
library(leaflet)
leaflet() %>%
addTiles() %>%
addPolygons(data = sf)
library(googleway)
set_key("YOUR_GOOGLE_MAP_KEY")
google_map() %>%
add_polygons(data = sf)
Upvotes: 0
Reputation: 5913
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)
Upvotes: 3