Search code examples
rrastergoogle-maps-static-apiggmap

Finding the boundary points in a raster data file


So, I have with me the center point and the zoom level.
I have to plot some points on the map.

The map is stored in a raster data file, and is displayed on the R's widget.

The issue is that when a point is received, I need to check whether it falls inside the data of this raster file or not.
If the point is in the raster file, then I can safely plot it.
If not, then I need to load another raster file which contains that point, and then plot the point.

The raster package of R has a function named as.data.frame which loads the raster data into the data frame.

Is it possible, then, to figure out which points (lats and lons) are at the four corners? Am I on the right track?


Solution

  • If your data is of RasterLayer class then extent will give you the extent of the raster and xmin, 'min, ymax and xmax to access the various slots.

    eg

    # create a dummy raster
    r1 <- raster(nrows=108, ncols=21, xmn=0, xmx=10)
    r1[] <-1
    
    extent(r1)
    ## class       : Extent 
    ## xmin        : 0 
    ## xmax        : 10 
    ## ymin        : -90 
    ## ymax        : 90 
    

    You can access the various slots using

    xmin(r1)
    ## [1] 0
    xmax(r1)
    ##[1] 10
    ymin(r1)
    ## [1] -90
    ymax(r1)
    ## [1] 90
    

    If your data is a SpatialGridDataFrame then bbox will return the bounding box

    .grid <- as(r1,'SpatialGridDataFrame')
    
    bbox(.grid)
    ##    min max
    ## s1   0  10
    ##  2 -90  90
    

    Does my xy coordinate lie within the raster boundary

    you can use cellFromXY to find the cell id, and it will return NA if it is outside the extext

    eg

     # some data
     .points <- rbind(c(1,1),c(-4,1))
     # the first point lies within the raster, the second not
    
     # cell from XY will tell you this.
     cellFromXY(r1,.points)
     ## [1] 1116   NA
    

    EDIT for ggmap

    if you have a map acquired by get_map, it is a ggmap object, and will not work with the package raster without some help from you .

    you can obtain the bounding box as the bb attribute.

      hdf <- get_map()
      attr(hdf,'bb')
    ##    ll.lat    ll.lon   ur.lat    ur.lon
    ## 1 29.38048 -95.80204 30.14344 -94.92313
    

    A helper function that will create a RasterStack from a ggmap object

    ggmap_rasterlayer <- function(map){
      map_bbox <- attr(map, 'bb') 
      .extent <- extent(as.numeric(map_bbox[c(2,4,1,3)]))
      my_map <- raster(.extent, nrow= nrow(map), ncol = ncol(map))
      rgb_cols <- setNames(as.data.frame(t(col2rgb(map))), c('red','green','blue'))
      red <- my_map
      values(red) <- rgb_cols[['red']]
      green <- my_map
      values(green) <- rgb_cols[['green']]
      blue <- my_map
      values(blue) <- rgb_cols[['blue']]
      stack(red,green,blue)
    
    }
    
    my_map <- ggmap_rasterlayer(hdf)