If you have a data frame - there needs to be some way to create multiple polygons from a single data frame (by specifying a variable that defines them)
^^eg, given this df:
df <- data.frame(lat = c(36.1, 36, 36, 36.1, 36.1, 36, 36), lng = c(-94.17, -94.2, -94.14, -94.2, -94.14, -94.14, -94.2), shape = c("triangle", "triangle", "triangle", "square", "square", "square", "square"))
filtering on one polygon, this plots nicely:
df %>% filter(shape == "triangle") %>% leaflet() %>% addPolygons(lat = ~lat, lng = ~lng)
but this does not:
df %>% leaflet() %>% addPolygons(lat = ~lat, lng = ~lng)
Here is Hadley's shim:
l <- leaflet()
shapes <- unique(df$shape)
for (shape in shapes) {
d <- df[df$shape == shape, , drop = FALSE]
l <- l %>% addPolygons(lat = d$lat, lng = d$lng)
}
l
You could use this function to change the data frame to an sp::SpatialPolygons object, which works nicely with Leaflet:
library(dplyr)
library(sp)
library(leaflet)
dataframeToPolygons <- function(df, latCol, lngCol, idCol) {
SpatialPolygons(lapply(unique(df[[idCol]]), function(id) {
Polygons(list(Polygon(as.matrix(
df[df[[idCol]] == id, c(lngCol, latCol)]
))), id)
}))
}
df <- data.frame(lat = c(36.1, 36, 36, 36.1, 36.1, 36, 36), lng = c(-94.17, -94.2, -94.14, -94.2, -94.14, -94.14, -94.2), shape = c("triangle", "triangle", "triangle", "square", "square", "square", "square"))
df %>% dataframeToPolygons("lat", "lng", "shape") %>%
leaflet() %>% addPolygons()
How about exposing id as an additional formula style parameter so people can continue to work with data frames without having to deal with the intricacies of sp?
^did this ever get done? still seems like I need a for loop to iterate through and add multiple polygons. alternative is to use a spatial polygons data frame to create the leaflet object and then call addPolygons() but what if I just want to add the polygons to an existing map?
@sethneel You can do that, just pass a data argument to addPolygons: addPolygons(map, data = spobj, ...). Most layer functions in leaflet have a data parameter that overrides whatever you passed to leaflet() (if anything).
Most helpful comment
How about exposing
idas an additional formula style parameter so people can continue to work with data frames without having to deal with the intricacies of sp?