Search code examples
r

Getting latitude and longitude based on a location


I'm trying to get some latitudes and longitudes into my data based on locations which I do have and was wanted to know if there are any functions or packages that do this for my locations below? I have seen a package that looks potentially helpful called geocode but it requires an API code which I have no experience with at all.

locations = c('london','birmingham','madrid','paris','marseille')  

Solution

  • Here is a solution using tidygeocoder package:

    library(tidygeocoder)
    
    locations = c('london','birmingham','madrid','paris','marseille')  
    
    coordinates <- list()
    for(i in locations){
      coordinates[[i]] <- geo(i)
    }
    
    print(coordinates)
    
    $london
    # A tibble: 1 × 3
      address   lat   long
      <chr>   <dbl>  <dbl>
    1 london   51.5 -0.128
    
    $birmingham
    # A tibble: 1 × 3
      address      lat  long
      <chr>      <dbl> <dbl>
    1 birmingham  52.5 -1.90
    
    $madrid
    # A tibble: 1 × 3
      address   lat  long
      <chr>   <dbl> <dbl>
    1 madrid   40.4 -3.70
    
    $paris
    # A tibble: 1 × 3
      address   lat  long
      <chr>   <dbl> <dbl>
    1 paris    48.9  2.35
    
    $marseille
    # A tibble: 1 × 3
      address     lat  long
      <chr>     <dbl> <dbl>
    1 marseille  43.3  5.37