We are using the GADM data for France, and I'm curious if we can find the region of a point based on its latitude and longitude.
So I can plot a map of France using
library(raster)
fr = getData("GADM", country="FRA", level=1)
plot(fr)
The coordinates of a point in Paris is
latitude = 48.86122650866868
longitude = 2.341541835915652
Now when I look up different regions at level 1, I get
> fr$NAME_1
[1] "Auvergne-Rhône-Alpes" "Bourgogne-Franche-Comté" "Bretagne" "Centre-Val de Loire"
[5] "Corse" "Grand Est" "Hauts-de-France" "Île-de-France"
[9] "Normandie" "Nouvelle-Aquitaine" "Occitanie" "Pays de la Loire"
[13] "Provence-Alpes-Côte d'Azur"
Is it possible to extract the region of that coordinate, which should be Île-de-France?
CodePudding user response:
with package {sf}:
library(sf)
my_point <- st_point(c(2.3415, 48.86122))
## convert fr to class sf
fr <- st_as_sf(fr)
i <- st_within(my_point, fr)
fr[as.integer(i),]$NAME_1
output:
[1] "Île-de-France"
edit to check, map point and provinces with labels:
library(ggplot2)
## set coordinate reference system for my_point
## to EPSG 4326 (WGS84):
my_point <- st_sfc(my_point, crs = 4326)
fr %>%
ggplot(mapping = aes(geometry = geometry))
geom_sf()
geom_sf_label(aes(label = NAME_1))
geom_sf(my_point, mapping = aes(geometry = geometry))