Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Overlay image on R leaflet map

Tags:

python

r

leaflet

I have a .PNG image which fundamentally represents is raster, but is not in a raster format. These are provide to me, otherwise I would generate them as rasters myself and avoid this problem.

I would like to overlay the image on a leaflet basemap in R. The image overlay will just provide a reference for the user to draw a bounding box around a region, and query a database for the raw data that generated the raster in that region.

In Python's implementation of leaflet the image overlay is possible in this manner

center = [0,0]
zoom = 2

m = Map(center=center, zoom=zoom)
layer = ImageOverlay(url="filename.png", bounds=(( min_lat, min_lon), 
                                             (max_lat, max_lon)))
m.add_layer(layer)
return m

Thus far it looks like to do this in R, I need a raster object that then use addRasterImage(), which appears to converts the raster to a RGB image and then overlays it on the leaflet map. I have an image initially and just want add it as a layer rather than a requiring a raster format. Thank you.

like image 356
Nate Miller Avatar asked Nov 08 '17 02:11

Nate Miller


1 Answers

If you need to append the image and not change it afterwards (bbox or source), then you should be able to do that using htmlwidgets to access native leaflet.js:

The htmlwidget::onRender function can be used to add custom behavior to the leaflet map using native Javascript. This is a some what advanced use case and requires you to know Javascript. Using onRender you can customize your map’s behavior using any of the APIs as defined in the Leaflet.js documentation. (from leaflet r documentation)

This gives you a bit more flexibility by revealing the more extensive native functionality. To add an image overlay is rather straightforward (example) and similar to the python implementation. A simple example adopted from the r and js documentation versions might look like:

library(leaflet)

m <- leaflet() %>%
  addTiles() %>%  # Add default OpenStreetMap map tiles
  addMarkers(lng=-74.22655, lat=40.712216, popup="Bottom Right Corner") %>%
  htmlwidgets::onRender("
      function(el, x) {
        console.log(this);
        var myMap = this;
        var imageUrl = 'http://www.lib.utexas.edu/maps/historical/newark_nj_1922.jpg';
        var imageBounds = [[40.712216, -74.22655], [40.773941, -74.12544]];

        L.imageOverlay(imageUrl, imageBounds).addTo(myMap);
      }
      ")
m  # Print the map
like image 51
Andrew Reid Avatar answered Oct 31 '22 05:10

Andrew Reid