i am coding with R and RStudio. I have a set of polygons in one in my global environment called buek250_shapefile. I am able to plot them with leaflet.
For the next step I wrote a function which gets lat and lon values, and should give back information about the shape which haqs the shortest distance to the next polygon shape.
My problem: I always get back the same polygon shape for all lat lon values I am trying. And the computed distances are between 5000 and 7000km. But all my shapes and lat lon values are in Germany, and Germany is not so big.
My data: https://download.bgr.de/bgr/boden/BUEK250/shp/buek250_mg_utm_v55.zip
Can anyone here help me please?
Thank you very much
lowestdistancebuek <- function(inputlat, inputlon) {
# Modify the clicked point. Make the input data into CRS format
# Order is important: first lat, then lon
point <- st_point(c(inputlat, inputlon)) %>%
st_sfc(crs = 25832)
# Is there a shape containing the clickedpoint?
nearestshape <- st_intersects(point, buek250_shapefile_all, sparse = FALSE)
# nearestsape is a logical matrix. For every polygon it contains if the point is in or not
# Which polygon contains the point? Extract it
nearestshape <- which(nearestshape, arr.ind = TRUE)
# Extract the column
nearestshape <- nearestshape[,2]
# If there is a shape containing the point, nearestshape has length 1
# In this case, nearestshape is set to the sf
# Otherwise, the nearestshape is determinded and set to nearestshape
if(length(nearestshape) == 1) {
nearestshape <- buek250_shapefile_all[nearestshape, ]
} else if (length(nearestshape) == 0){ # no polygon contains the point
# Compute the distances between each polygon and the point. Result is saved in distances
distances <- st_distance(point, buek250_shapefile_all,
by_element = FALSE, # TRUE returns a vector
tolerance = TRUE # speeds up computing
)
# Which distance ist the smallest one?
nearestshape <- which.min(distances)
# The shortest number was saved in nearestshape, now there is saved the polygone information
nearestshape <- buek250_shapefile_all[nearestshape, ]
}
return(nearestshape)
}
Right now I receive for every input the same output. I expect the code to return the shapefile with the shortest distance to the given point.
odcoder is a new contributor to this site. Take care in asking for clarification, commenting, and answering.
Check out our Code of Conduct.