I am trying to assess if a point coordinate x,y is in a multipolygon obtain through api from osmdata library in R.
in dat1 I get the multipolygon from OSM. in ptCoord I enter the point to assess and set the crs.
both variable are sfc objects, however I can't seems to assess if the point is in the multipolygon using sf::st_contains
any help would be greatly appreciated, I spend over 2 hours browsing through the online documentation and ressources unsuccessfully.
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)
the results seems to be right, the point is not in the polygon, see:
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)
The plot shows that ptCoord
is not in poly
, so the results is empty. See how this would behave if we select a point that is in the polygon (I sample this with 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
So in this case the result is that alt
is contained in the polygon 1
ot the object poly
Created on 2023-04-18 with reprex v2.0.2