Introduction

A collection of functions to visualize spatial data and models on top of static maps from various online sources like Google Maps. It includes tools common to those tasks, including functions for geolocation and routing. ggmap
In order to use R library ggmaps with Google map objects, you will need to create a Google Cloud Platform account which grants access to Google Map APIs like ‘Geocoding’ and ‘Static Maps’. Additional Details can be found here
As of the date of publishing this tutorial, Google is offering a Free Trial for the API service.

Google Cloud Platform

  1. Activate your Google account

  2. Create Credentials (API key)

    • Search for Google Maps Platform, select Google Maps Platform

    • Select “Credentials” tab on the left, select +CREATE CREDENTIALS -> API key

    • copy your API key

  3. Enable Geolocation & Static Maps APIs

    • Select “APIs” tab on the left

    • Select “Maps Static API” -> ENABLE button

    • Select “Geolocation API” -> ENABLE button

Include libraries & Google API key

library(tidyverse)
## -- Attaching packages --------------------------------------- tidyverse 1.3.1 --
## v ggplot2 3.3.5     v purrr   0.3.4
## v tibble  3.1.5     v dplyr   1.0.7
## v tidyr   1.1.4     v stringr 1.4.0
## v readr   2.0.2     v forcats 0.5.1
## -- Conflicts ------------------------------------------ tidyverse_conflicts() --
## x dplyr::filter() masks stats::filter()
## x dplyr::lag()    masks stats::lag()
tidyverse_logo()
## * __  _    __   .    o           *  . 
##  / /_(_)__/ /_ ___  _____ _______ ___ 
## / __/ / _  / // / |/ / -_) __(_-</ -_)
## \__/_/\_,_/\_, /|___/\__/_/ /___/\__/ 
##      *  . /___/      o      .       *
# install package first time use -> install.packages('ggmap')
library(ggmap)
## Google's Terms of Service: https://cloud.google.com/maps-platform/terms/.
## Please cite ggmap if you use it! See citation("ggmap") for details.
# Active Google Maps API. Use option 'write = TRUE' to make environment variable for all R sessions.

# Uncomment this line
# ggmap::register_google(key = "your copied Google map API key", write = TRUE)

Make a Google Map

ggmap_sf <- ggmap::get_googlemap('San Francisco', zoom = 12)
## Source : https://maps.googleapis.com/maps/api/staticmap?center=San%20Francisco&zoom=12&size=640x640&scale=2&maptype=terrain&key=xxx
## Source : https://maps.googleapis.com/maps/api/geocode/json?address=San+Francisco&key=xxx
ggmap(ggmap_sf)

ggmap_center <- ggmap::get_googlemap(center = c(lon = -122.444810, lat = 37.762445), 
                                     zoom = 12,
                                     maptype = 'hybrid',
                                     color = "color")
## Source : https://maps.googleapis.com/maps/api/staticmap?center=37.762445,-122.44481&zoom=12&size=640x640&scale=2&maptype=hybrid&key=xxx
ggmap(ggmap_center)

Add Styles

Generated maps will have Styles consisting of Features and Elements which adhere to Rules.
Example: color the streets purple, add a style to the map.
ggmap(get_googlemap('San Francisco', zoom = 13,
                    style = paste0("feature:road|element:all|color:0xC280E9")))

To add more styles, concatenate the style string with a new style.
ggmap(get_googlemap('San Francisco', zoom = 13,
                    style = paste0("feature:road|element:all|color:0xC280E9",
                                   "&style=feature:water|element:all|color:0x7FFF00")))

Turn off all ‘labels’ associated with all ‘features’.
ggmap(get_googlemap('San Francisco', zoom = 13, 
                    style = paste0("feature:all|element:labels|visibility:off")))

Add Data Points to the Map

Here is some Geospatial data gathered from #TidyTuesday dataset about tree location in San Francisco. Each tree has a longitude/latitude coordinate as an attribute.
sf_trees <- readr::read_csv('https://raw.githubusercontent.com/rfordatascience/tidytuesday/master/data/2020/2020-01-28/sf_trees.csv') %>% 
    drop_na() %>% 
    filter(legal_status == "DPW Maintained")

glimpse(sf_trees)
## Rows: 18,141
## Columns: 12
## $ tree_id      <dbl> 30372, 30460, 30454, 30428, 30468, 30470, 30490, 53227, 5~
## $ legal_status <chr> "DPW Maintained", "DPW Maintained", "DPW Maintained", "DP~
## $ species      <chr> "Ulmus parvifolia :: Chinese Elm", "Pittosporum undulatum~
## $ address      <chr> "498x Arkansas St", "470 Union St", "381 Union St", "434 ~
## $ site_order   <dbl> 1, 1, 1, 1, 2, 3, 4, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, ~
## $ site_info    <chr> "Sidewalk: Curb side : Cutout", "Sidewalk: Curb side : Cu~
## $ caretaker    <chr> "Private", "Private", "Private", "Private", "Private", "P~
## $ date         <date> 1956-03-02, 1956-05-11, 1956-05-11, 1956-05-11, 1956-05-~
## $ dbh          <dbl> 10, 19, 8, 13, 8, 8, 16, 13, 20, 12, 36, 14, 27, 11, 11, ~
## $ plot_size    <chr> "3x3", "4x4", "3x3", "7x3", "3x3", "3x3", "3x3", "3x3", "~
## $ latitude     <dbl> 37.76005, 37.80074, 37.80081, 37.80082, 37.80061, 37.8006~
## $ longitude    <dbl> -122.3983, -122.4073, -122.4057, -122.4066, -122.4073, -1~
Lets look at the trees maintained by the San Francisco Department of Public Works
sf_trees %>%
    ggplot(aes(longitude, latitude)) +
    geom_point(color = 'green', alpha = 0.42)

This plot looks somewhat like San Francisco, it’s a very densly populated scatter plot. Because ggmap is built on top of ggplot2, we can plot a data point layer (geometry) on top of the Google map.
ggmap(get_googlemap(center = c(lon = -122.444810, lat = 37.762445), zoom = 12, 
                    style = paste0("feature:all|element:labels|visibility:off"))) +
    geom_point(data = sf_trees, aes(longitude, latitude), 
               color = 'green',
               size = 0.42,
               alpha = 0.42)

Add Heatmap

There are too many trees, the data points look very cluttered on top of the map. Instead, we can do a density map which group points by count and create density contours. A low concentration of trees will be filled by green while a high population will be red. Increase bins for a greater blending effect.
ggmap(get_googlemap(center = c(lon = -122.444810, lat = 37.762445), zoom = 12, 
                    style = paste0("feature:all|element:labels|visibility:off"))) +
    stat_density2d(data = sf_trees, aes(longitude, latitude, fill = ..level..), 
                   geom = "polygon", alpha = 0.42) +
    scale_fill_gradient(low = "green", high = "red", guide = "none")

Custom

ggmap(get_googlemap(center = c(lon = -122.444810, lat = 37.762445), 
                    zoom = 13,
                    maptype = 'hybrid',
                    style = paste0("feature:all|element:labels|visibility:off"))) +
    stat_density2d(data = sf_trees, 
                   aes(longitude, latitude, fill = ..level.., alpha = ..level..), 
                   bins = 17, geom = 'polygon') +
    scale_fill_gradient(low = "blue", high = "green", guide = "none") +
    scale_alpha(guide = "none") +
    labs(x = '', y = '', title = "San Francisco Trees Maintained by the Department of Public Works")
## Warning: Removed 3539 rows containing non-finite values (stat_density2d).

Assassin’s Creed

interactive map - googleway::google_map()