R for leaflet redirect when clicking on raster ima

2019-07-09 04:22发布

问题:

I'm using leaflet for R and I simply would like to be redirected on some URL when I click on the raster image. My current code is the following :

library(htmlwidgets)
library(raster)
library(leaflet)
library(sp)

imgPath = paste(projectPath,"/test.tif", sep = "")
outPath = paste(projectPath, "/leaflethtmlgen.html", sep="")

r <- raster(imgPath)

pal <- colorNumeric(c("#FF0000", "#666666", "#FFFFFF"), values(r),
                    na.color = "transparent")

m <- leaflet() 
m <- addTiles(m) 
m <- addRasterImage(m,r, colors=pal, opacity = 0.9, maxBytes = 123123123, group = "Raster1") 
m <- addLegend(m,pal = pal, values = values(r), title = "Test")

m <-  addLayersControl(
    m, 
    overlayGroups = c("Raster1"),
    options = layersControlOptions(collapsed = FALSE)
  )
m

The result is the following:

回答1:

You could use viewExtent from the mapview package for that:

library(mapview)
mapview(poppendorf[[10]]) +
  viewExtent(poppendorf[[10]], 
             opacity = 0, fillOpacity = 0, 
             popup = '<a href="http://www.google.com">Search Google</a>')

viewExtent does as the name suggests draw a rectangle around the the extent of a raster image (or any spatial object form the sp package). By setting the line and fill opacity to zero and providing a custom popup you can achieve something that is pretty close to what you want. I am not aware of any way to directly link hyperlinks to raster objects in leaflet for R.

HTH, Tim