Reputation: 3
My problem: I would like to get city names from shapefile using many longitude and latitude data. Some lattitude and longitude will not necessarily be at the center of the polygon (city), but in some part of the polygon. I mean, I do not know which city this points belongs, this is what I want to know. In the shape file have the name of each polygon that belong at the respective City.
I know that Google and others API's are paid and/or limited. I prefere to get from shapefile.
[link to shapfile (cities) from São Paulo state in Brazil] (geoftp.ibge.gov.br/organizacao_do_territorio/malhas_territoriais/malhas_municipais/municipio_2020/UFs/SP/SP_Municipios_2020.zip)
Some points examples:
'coord <- data.frame( "lon" = c(-48.1766, -50.078,, -52.958, -51.3837, -50.2466, -47.0006, -47.8348, -45.0857), "lat" = c(-21.7946, -21.4209, -22.482, -20.8939, -20.2834, -21.4708, -24.4881, -23.4339))'
Upvotes: 0
Views: 526
Reputation: 5232
For some reason library revgeo
(reverse geocoding using Photon geocoder) is not working for me currently. You can try something like this:
library(tidyverse)
library(rjson)
coord %>%
select(lon, lat) %>%
imap(~str_c(.y, "=", .x)) %>%
pmap(~str_c(c(...), collapse = "&")) %>%
str_c("https://photon.komoot.io/reverse?", .) %>%
map(~rjson::fromJSON(file = .x)) %>%
map(~pluck(.x, "features", 1, "properties")) %>%
map_dfr(~.x[c("country", "city", "county", "district", "state")]) %>%
cbind(coord, .)
lon lat country city county district state
1 -48.1766 -21.7946 Brasil Araraquara Região Geográfica Intermediária de Araraquara Vila Melhado São Paulo
2 -50.0780 -21.4209 Brasil Penápolis Região Geográfica Intermediária de Araçatuba Penápolis São Paulo
3 -52.9580 -22.4820 Brasil Rosana Região Geográfica Intermediária de Presidente Prudente Rosana São Paulo
4 -51.3837 -20.8939 Brasil Andradina Região Geográfica Intermediária de Araçatuba Vila Peliciari São Paulo
5 -50.2466 -20.2834 Brasil Fernandópolis Região Geográfica Intermediária de São José do Rio Preto Coester São Paulo
6 -47.0006 -21.4708 Brasil Mococa Região Geográfica Intermediária de Campinas Centro São Paulo
7 -47.8348 -24.4881 Brasil Registro Região Geográfica Intermediária de Sorocaba Vila Paraguai São Paulo
8 -45.0857 -23.4339 Brasil Ubatuba Região Metropolitana do Vale do Paraíba e Litoral Norte Jardim Carolina São Paulo
Using shape file:
library(sf)
shp_df <- read_sf(data_path)
st_coord <- st_as_sf(coord, coords = c("lon", "lat"), crs = st_crs(shp_df))
coord$city <- shp_df[unlist(st_within(st_coord, shp_df)),]$NM_MUN
coord
lon lat city
1 -48.1766 -21.7946 Araraquara
2 -50.0780 -21.4209 Penápolis
3 -52.9580 -22.4820 Rosana
4 -51.3837 -20.8939 Andradina
5 -50.2466 -20.2834 Fernandópolis
6 -47.0006 -21.4708 Mococa
7 -47.8348 -24.4881 Registro
8 -45.0857 -23.4339 Ubatuba
where data_path
is path to SP_Municipios_2020.shp
.
Upvotes: 0