坐标为x,y的点是否在R中的osmdata多多边形内?

n9vozmp4  于 2023-04-27  发布在  其他
关注(0)|答案(1)|浏览(129)

我试图评估一个点的坐标x,y是否在一个多多边形中,这个多多边形是通过R中的osmdata库中的API获得的。
在dat1中,我从OSM中获取多面。在ptCoord中,我输入要评估的点并设置crs。
这两个变量都是sfc对象,但是我似乎不能使用sf::st_contains来评估点是否在多面中
任何帮助将不胜感激,我花了2个多小时浏览在线文档和资源不成功。

dat1 <- opq_osm_id (type = "relation", id = 1237758) %>%
    opq_string () %>%
    osmdata_sf ()

ptCoord <- ptCoord = st_sfc(st_point(c(10.713097, 47.54761)), crs = 4326)

sf::st_contains(dat1$osm_multipolygons, ptCoord)
#Sparse geometry binary predicate list of length 1, where the predicate
#was `contains'
#1: (empty)
igetnqfo

igetnqfo1#

结果似乎是对的,点不在多边形中,请参见:

library(osmdata)
#> Data (c) OpenStreetMap contributors, ODbL 1.0. https://www.openstreetmap.org/copyright
library(sf)
#> Linking to GEOS 3.8.0, GDAL 3.0.4, PROJ 6.3.1; sf_use_s2() is TRUE
library(ggplot2)

dat1 <- opq_osm_id(type = "relation", id = 1237758) %>%
  opq_string() %>%
  osmdata_sf()

poly <- st_transform(dat1$osm_multipolygons, 4326)
#> Warning in CPL_transform(x, crs, aoi, pipeline, reverse, desired_accuracy, :
#> GDAL Error 1: PROJ: proj_as_wkt: DatumEnsemble can only be exported to
#> WKT2:2019


ptCoord <- st_sfc(st_point(c(10.713097, 47.54761)), crs = 4326)
sf::st_contains(poly, ptCoord)
#> Sparse geometry binary predicate list of length 1, where the predicate
#> was `contains'
#>  1: (empty)

sf::st_contains(poly, ptCoord, sparse = FALSE)
#>      [,1]
#> [1,] FALSE

ggplot(poly) +
  geom_sf() +
  geom_sf(data = ptCoord)

图中显示ptCoord不在poly中,因此结果为空。看看如果我们选择多边形中的一个点会如何表现(我用st_sample()对此进行了采样)

# Check alt
set.seed(1234)
alt <- st_sample(poly, size=1)

ggplot(poly) +
  geom_sf() +
  geom_sf(data = alt)

# This one is contained

sf::st_contains(poly, alt)
#> Sparse geometry binary predicate list of length 1, where the predicate
#> was `contains'
#>  1: 1

sf::st_contains(poly, alt, sparse = FALSE)
#>      [,1]
#> [1,] TRUE

因此,在这种情况下,结果是alt包含在对象poly的多边形1
创建于2023-04-18带有reprex v2.0.2

相关问题