Identify position of a click on a raster in leaflet, in R

后端 未结 1 1699
孤独总比滥情好
孤独总比滥情好 2021-02-08 23:05

I am plotting a large lat-lon NetCDF raster over an R leaflet map using shinydashboard. When I click on the map, a popup comes out and sho

1条回答
  •  悲&欢浪女
    2021-02-08 23:14

    I have found that I can reproject back the X-Y (lon-lat) position given by input$map_click. In this case I assumed the input projection to be Lon-Lat, but I think it doesn't necessarily have to be. It just needs to have Lat-Lon units.

    #Set projections
    inputProj <- "+proj=longlat +datum=WGS84 +ellps=WGS84 +towgs84=0,0,0"
    leafletProj <- "+proj=merc +lon_0=0 +k=1 +x_0=0 +y_0=0 +a=6378137 +b=6378137 +towgs84=0,0,0,0,0,0,0 +units=m +nadgrids=@null +wktext +no_defs"
    #Note that for some reason "+nadgrids=@null +wktext" is very important
      #as hinted to by other questions and answers linked in my question.
    xy <- SpatialPoints(data.frame(x,y))
    proj4string(xy) <- inputProj
    xy <- as.data.frame(spTransform(xy, leafletProj))
    #Get the cell number from the newly transformed metric X and Y.
    cell <- cellFromXY(depth, c(xy$x, xy$y))
    
    #At this point, you can also retrace back the center of the cell in
      #leaflet coordinates, starting from the cell number!
    xy <- SpatialPoints(xyFromCell(depth, cell))
    proj4string(xy) <- leafletProj
    xy <- as.data.frame(spTransform(xy, inputProj))
    #Here XY will again be in lat-lon, if you projection says so,
      #indicating the center of the clicked cell
    

    0 讨论(0)
提交回复
热议问题