Search code examples
rgoogle-mapsopenstreetmapshapefilegooglevis

Overlaying shapefiles or raster over interactive maps


I'm using R, and I want to overlay some raster data (e.g. a temperature map from a model) over an interactive map which allows panning and zooming. Ideally, I'd like to overlay over Google Maps or OpenStreetMaps. The input data can be in shapefiles, KML, raster data or whatever comes in handy.

  • I know I can easily do this non-interactively using either googleVis, ggmap or RgoogleMaps. But I do not want to use tiles, I want interaction! Zooming, panning etc., directly from the browser.

  • googleVis, as far as I know, unfortunately only allows to show interactively points or addresses, not areas.

  • This question is very similar but I definitely want to try to do this using R. I can create the KML or geoJSON from R, but how do I overlay it from R directly?

  • OpenStreetMaps is also fine, however I've not found any reference on how to overlay data over it from R, despite the fact that OSM seems to have a pretty straightforward API.


Solution

  • The leaflet package may be of interest for you. You can easily add a raster object. From the documentation

    Two-dimensional RasterLayer objects (from the raster package) can be turned into images and added to Leaflet maps using the addRasterImage function.

    And here is an example also from the documentation:

    library(leaflet)
    library(raster)
    
    r <- raster("nc/oisst-sst.nc")
    pal <- colorNumeric(c("#0C2C84", "#41B6C4", "#FFFFCC"), values(r),
      na.color = "transparent")
    
    leaflet() %>% addTiles() %>%
      addRasterImage(r, colors = pal, opacity = 0.8) %>%
      addLegend(pal = pal, values = values(r),
        title = "Surface temp")