Tutorials

Learn how to use R.

Required tools


First we need the ggmap library. Don’t forget to install it first by using install.packages( ‘ggmap’ ).

library( 'ggmap' ) # includes functions geocode(), get_map(), and ggmap()
  • geocode() finds latitude and longitude corresponding to keywords.

  • get_map() queries Google Maps, OpenStreetMap, Stamen Maps or Naver Map servers for a map.

  • ggmap() will display the map.

loading a map


Specify your location using geocodes

In order to find longitude and latitude you can first go to Google Map. The coordinates in the address bar correspond to the center of the map. The coordinates at the bottom of the page correspond to the location of your pin.

my_loc <- c( lon = 0, lat = 0 ) 
long_lake <- c( lon = -124.0189453, lat = 49.2109882 )
viu_loc <- geocode( 'woodgrove, nanaimo' )
( sh_loc <- geocode( 'Shanghai' ) )
##        lon      lat
## 1 121.4737 31.23039

Downloading maps

We use the function get_map() to download the map. The first argument is the location. The source argument is for the map server. Zoom gives us the area of the map. The zoom argument should be an integer from 3 (continent) to 21 (building), default value 10 (city). Finally, maptype is the theme, but note that different source have different themes. Here is two sources with their respective themes.

  • stamen maptype = ‘terrain’, ‘toner’, or ‘watercolor’

  • google maptype = ‘roadmap’, ‘terrain’, ‘satellite’, ‘hybrid’

We download three maps. One for each of the locations, my_loc, viu_loc, sh_loc.

my_map <- get_map( location = my_loc, 
                     source = 'stamen', 
                     zoom = 4,
                     maptype = c('toner') )
viu_map <- get_map( location = viu_loc, 
                      source = 'google', 
                      zoom = 14,
                      maptype = c('roadmap') )
sh_map <- get_map( location = sh_loc, 
                     source = 'google', 
                     zoom = 12,
                     maptype = c('satellite') )

Display a map


To display the maps we use the function ggmap().

First a map from Stamen with toner

ggmap( my_map )

Second a map from Google with roadmap

ggmap( viu_map )

Finally a map from Google with satellite

ggmap( sh_map )