Leaflet: addPolygons can only add a single polygon

Created on 31 Jan 2016  路  5Comments  路  Source: rstudio/leaflet

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)

Most helpful comment

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?

All 5 comments

^^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).

Was this page helpful?
0 / 5 - 0 ratings

Related issues

BilboBaagins picture BilboBaagins  路  3Comments

BastienFR picture BastienFR  路  5Comments

jz1584 picture jz1584  路  3Comments

loerasg picture loerasg  路  6Comments

okjed picture okjed  路  6Comments