I have a latitude and longitude
locs <- structure(list(Latitude = 0.176094639, Longitude = 117.4955225), row.names = 1L, class = "data.frame")
I want to convert this into a square polygon grid with dimension of 5 km X 5 km and save the shapefile. I can't seem to find a function in R to do this and wondering if anyone has done similar work?
CodePudding user response:
Assuming that the point you provided is the center of the grid you want,
- make the point an sf object
- buffer it by 2.5km
- get the bounding box of the buffer
- make a grid (10x10 used below)
- write the shapefile(commented out)
library(sf)
library(tidyverse) # pipe & plotting
locs <- structure(list(Latitude = 0.176094639, Longitude = 117.4955225), row.names = 1L, class = "data.frame")
# Make the point an sf object
locs_sf <- locs %>%
st_as_sf(coords = c('Longitude', 'Latitude')) %>%
st_set_crs(4326)
# get the bounding box of a 2500m buffered circle around the point
box <- st_buffer(locs_sf, 2500) %>%
st_bbox() %>%
st_as_sfc()
# make a 10x10 grid of the bounding box
grid <- st_make_grid(box, n = c(10,10))
# Use st_write() to write your shapefile
#st_write(grid, '/path/to/file.shp')
ggplot()
geom_sf(data = locs_sf, color = 'red', size = 5)
geom_sf(data = grid, fill = NA, color = 'black')
Created on 2022-03-24 by the reprex package (v2.0.1)