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

大憨熊 提交于 2019-12-03 08:11:51

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
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!