How to retrieve GPS coordinates with OSM?

89 Views Asked by At

I would like to use the OpenStreetMap API to search GPS coordinates of cities. I would like to be able to retrieve these coordinates with zip codes, but I would also like to be able to do so with city names.

The issue is that the API's URL is no longer valid !

My function is :

mygeocode <- function(adresses){
  nominatim_osm <- function(address = NULL){
    ## details: http://wiki.openstreetmap.org/wiki/Nominatim
    ## fonction nominatim_osm proposée par D.Kisler
    if(suppressWarnings(is.null(address)))  return(data.frame())
    tryCatch(
      d <- jsonlite::fromJSON(
        gsub('\\@addr\\@', gsub('\\s+', '\\%20', address),
             'http://nominatim.openstreetmap.org/search/@addr@?format=json&addressdetails=0&limit=1')
      ), error = function(c) return(data.frame())
    )
    if(length(d) == 0) return(data.frame())
    return(c(as.numeric(d$lon), as.numeric(d$lat)))
  }
  tableau <- t(sapply(adresses,nominatim_osm))
  colnames(tableau) <- c("lon","lat")
  return(tableau)
}````
1

There are 1 best solutions below

0
margusl On

If you trigger that query in your browser (e.g. http://nominatim.openstreetmap.org/search/Helsinki,%20Finland?format=json&addressdetails=0&limit=1 ) you'll be advised on changes you should make:

https://nominatim.openstreetmap.org/search?q=Helsinki,%20Finland&format=json&addressdetails=0&limit=1

Though you can also pick some client library, {tidygeocoder} for example:

library(dplyr, warn.conflicts = FALSE)
library(tidygeocoder)
library(sf)
#> Linking to GEOS 3.11.2, GDAL 3.6.2, PROJ 9.2.0; sf_use_s2() is TRUE
library(mapview)

# create a dataframe with addresses
cities <- tibble::tribble(
  ~city,
  "Helsinki, Finland",
  "Stockholm, Sweden",
  "Oslo, Norway"
)

lat_lon <- cities %>%
  geocode(city, method = 'osm', lat = latitude , long = longitude)
#> Passing 3 addresses to the Nominatim single address geocoder
#> Query completed in: 3.1 seconds
lat_lon
#> # A tibble: 3 × 3
#>   city              latitude longitude
#>   <chr>                <dbl>     <dbl>
#> 1 Helsinki, Finland     60.2      24.9
#> 2 Stockholm, Sweden     59.3      18.1
#> 3 Oslo, Norway          59.9      10.7

lat_lon %>% 
  st_as_sf(coords = c("longitude", "latitude"), crs = "WGS84") %>% 
  mapview()

Created on 2023-10-30 with reprex v2.0.2