ramnathv / rMaps

Interactive Maps from R
http://rmaps.github.io
389 stars 194 forks source link

Leaflet vector layers (Polygon, Rectangle, ...) #17

Open HarlanH opened 10 years ago

HarlanH commented 10 years ago

Hi, for a talk I'm giving very soon, it'd be really great to have a way to overlay polygons and tile-type heat maps on Leaflet maps. It looks like Leaflet supports Polygon and Rectangle layers, which could meet my needs. (GeoJSON seems like another viable option, but I've had trouble getting GeoJSON polygons to work, and a higher-level interface would be preferable.) How difficult will it be to add rMaps wrappers around the appropriate Leaflet functions?

ramnathv commented 10 years ago

@HarlanH Can you provide me with a link to a leaflet map that has the features that you are looking for? It is easier to work with something concrete, since Leaflet is an ocean in itself.

HarlanH commented 10 years ago

OK, for starters, this isn't working: https://gist.github.com/HarlanH/9243630 I can't tell where the problem is. The Javascript that you're generating looks OK to me, but it's causing a weird error in the Leaflet library, so presumably there's something slightly off. I'm just trying to draw a triangle.

ramnathv commented 10 years ago

Here is a modified version of your code that works for me. Key changes made:

Overall Conclusion: geoJSON is a pain to get right in JSON. If people were to use rMaps, I would need to make it super easy to create different geoJSON structures from simple data frames :)

library(plyr)
library(rMaps)

venues <- structure(list(
  name = c("pivotal", "aol", "columbia", "pivotal"), 
  lat = c(40.7403372, 40.7308948, 40.8074358, 40.7403372), 
  lon = c(-73.9951462, -73.9917096, -73.9625858,-73.9951462)), 
  .Names = c("name", "lat", "lon"), 
  row.names = c(NA, -4L), 
  class = "data.frame"
)

times_square <- c(40.7577, -73.9857)

map <- Leaflet$new()
map$setView(times_square, zoom = 10)

mk_polygon <- function(lats, lons){ 
  stopifnot(length(lats)==length(lons))
  coord_list <- llply(seq_along(lats), function(i) c(lons[[i]], lats[[i]]))
  list(
    type = 'Feature',
    properties = list(name = 'mypolygon'),
    geometry = list(
      type = 'Polygon', 
      coordinates = list(coord_list)
    )
  )
}
polygons <- mk_polygon(venues$lat, venues$lon)
map$geoJson(list(polygons))