Search code examples
rggplot2ggmappostal-code

How to extract longitude and latitude using postal code and `ggmap` function


I have a list of postal codes and I want to find their associated longitude and latitude in order to plot them on a map. For example, I showed couple of postal codes below:

code <- c("V6G 1X5", "V6J 2A4", "V5V 3N2")

Now, I want to find longitude and latitude for each of these postal code using ggmap function. How can I do this?


Solution

  • With ggmap::geocode(). Note that you might need to register you Google maps API key first. See https://rdrr.io/cran/ggmap/man/register_google.html

    library(ggmap)
    library(tidyverse)
    #register_google(key = "your_api_key_here") 
    
    code <- c("V6G 1X5", "V6J 2A4", "V5V 3N2")
    
    df_points <- ggmap::geocode(location = code)
    map_vancouver <- get_googlemap(center = "Vancoucer, BC, Canada", zoom = 13)
    
    ggmap(map_vancouver) +  geom_point(data = df_points, aes(x = lon, y = lat), colour = "red")
    

    enter image description here