I have imported a shapefile (.shp) into R to define a set of polygons. The shapefile takes the form of a grouped dataframe with ageometry
column containing a MULTIPOLYGON list of XY coordinates. I have added some extra columns of data to this dataframe:
ID Value geometry
A 5 MULTIPOLYGON (((519270 1639...
B 10 MULTIPOLYGON (((519553 1642...
C 25 MULTIPOLYGON (((519000 1666...
This works fine for generating static choropleth maps using ggplot
and geom_sf
. However, to generate dynamic maps using leaflet
I need to convert the XY coordinates that define the polygons into lat/long coordinates.
I have tried using st_transform
to do this and, while it does generate a set of polygons, I cannot colour those polygons as there are no values associated with them:
inter_map2 <- leaflet(df) %>%
addProviderTiles(providers$CartoDB.Positron) %>%
addPolygons(data = st_transform(df$geometry, 4326), stroke = TRUE, weight = 0.5, opacity = 1, fillOpacity = 0.05, highlightOptions = highlightOptions(color = "red", weight = 2, bringToFront = TRUE))
I have also tried using extract
but leaves the resulting lat and long columns with NA
values:
df_latlong <- df %>%
extract(geometry, c('lat', 'lon'), '\\((.*), (.*)\\)', convert = TRUE)
Is there a way to do this while also retaining the ID
and Value
columns associated with the polygons?