在 R 中创建等距空间网格

Creating an equal distance spatial grid in R

我正在尝试使用 R 在给定区域上制作一个等尺寸的正方形网格。我希望我的网格为 1km x 1km 的正方形。我看到这样的示例说明了相等的 lat/long 网格:

但这还不够大。看起来我应该能够使用 st_make_grid 函数并创建它,但我无法理解如何将网格制作为 1km x 1km。

https://r-spatial.github.io/sf/reference/st_make_grid.html

例如,我想从 (37,-89.2) 开始并在 (36.2,-86.8) 结束,并创建一个 1km x 1km 的均匀分布的网格。我将如何使用 R 来做到这一点?

注意:看起来棘手的部分是在非常大的区域上保持 1km x 1km 的网格。我可以使网格在十进制度数中保持相等的尺寸,但这在地面上的距离不相等。

我已经能够使用 PostGIS 做到这一点,多亏了 crafty answer here. 在 PostGIS 中我创建了一个函数:

CREATE OR REPLACE FUNCTION public.makegrid_2d (
  bound_polygon public.geometry,
  width_step integer,
  height_step integer
)
RETURNS public.geometry AS
$body$
DECLARE
  Xmin DOUBLE PRECISION;
  Xmax DOUBLE PRECISION;
  Ymax DOUBLE PRECISION;
  X DOUBLE PRECISION;
  Y DOUBLE PRECISION;
  NextX DOUBLE PRECISION;
  NextY DOUBLE PRECISION;
  CPoint public.geometry;
  sectors public.geometry[];
  i INTEGER;
  SRID INTEGER;
BEGIN
  Xmin := ST_XMin(bound_polygon);
  Xmax := ST_XMax(bound_polygon);
  Ymax := ST_YMax(bound_polygon);
  SRID := ST_SRID(bound_polygon);

  Y := ST_YMin(bound_polygon); --current sector's corner coordinate
  i := -1;
  <<yloop>>
  LOOP
    IF (Y > Ymax) THEN  
        EXIT;
    END IF;

    X := Xmin;
    <<xloop>>
    LOOP
      IF (X > Xmax) THEN
          EXIT;
      END IF;

      CPoint := ST_SetSRID(ST_MakePoint(X, Y), SRID);
      NextX := ST_X(ST_Project(CPoint, , radians(90))::geometry);
      NextY := ST_Y(ST_Project(CPoint, , radians(0))::geometry);

      i := i + 1;
      sectors[i] := ST_MakeEnvelope(X, Y, NextX, NextY, SRID);

      X := NextX;
    END LOOP xloop;
    CPoint := ST_SetSRID(ST_MakePoint(X, Y), SRID);
    NextY := ST_Y(ST_Project(CPoint, , radians(0))::geometry);
    Y := NextY;
  END LOOP yloop;

  RETURN ST_Collect(sectors);
END;
$body$
LANGUAGE 'plpgsql';

然后我可以调用它并传递一个多边形:

SELECT (
    ST_Dump(
      makegrid_2d(
        ST_GeomFromText(
          'Polygon((-75 42, -75 40, -73 40, -73 42, -75 42))',
          4326
        )  ,
         1000, -- width step in meters
         1000  -- height step in meters
       ) 
    )
  ) .geom AS cell into test_grid_cell;

但是正如您所见,即使使用 PostGIS,这也不是固定的例程。通过一些努力,我想我可以将其移植到 sf,但我对此并不过分兴奋...

考虑这个例子;它使用布拉格市的边界作为网格的基础。

关键部分是确保您的 sf 对象在公制 CRS 中(如果您是美国人并且有爱国心,则为英制 CRS);只要它在预计的 CRS 中(即 st_is_longlat(x) returns FALSE),哪个并不重要。

library(dplyr)
library(RCzechia) # a package of Czech administrative areas
library(sf)


mesto <- kraje() %>% # All Czech NUTS3 ...
  filter(NAZ_CZNUTS3 == 'Hlavní město Praha') %>% # ... city of Prague
  st_transform(5514) # a metric CRS 

grid_spacing <- 1000  # size of squares, in units of the CRS (i.e. meters for 5514)

polygony <- st_make_grid(mesto, square = T, cellsize = c(grid_spacing, grid_spacing)) %>% # the grid, covering bounding box
  st_sf() # not really required, but makes the grid nicer to work with later

plot(polygony, col = 'white')
plot(st_geometry(mesto), add = T)