Created
March 1, 2023 15:58
-
-
Save bbdaniels/67d4b1e15275775feba24c254ff57890 to your computer and use it in GitHub Desktop.
Make map images reproducibly using google maps API in R
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
id | latitude | longitude | type | |
---|---|---|---|---|
1 | 38.922893 | -77.06741979 | T | |
2 | 38.92846854 | -77.03038385 | T | |
3 | 38.90462752 | -77.0336025 | C | |
4 | 38.90776671 | -77.00978448 | C | |
5 | 38.87686969 | -77.01313188 | T |
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
# Map a Google Map with Satellite Basemap | |
# Setup ------------------------------------------------------------------------ | |
## Packages | |
library(dplyr) | |
library(ggmap) | |
library(ggplot2) | |
library(readr) | |
## Register Google Key | |
register_google(key = "API-KEY-HERE") | |
# Data and bounding box -------------------------------------------------------- | |
## Load data | |
df <- read_csv("~/Desktop/gmap/data.csv") | |
## Make variables for bounding box | |
ext <- 2/111 # extend bounding box by roughly 2 kilometers | |
lon_min <- min(df$longitude) - ext | |
lon_max <- max(df$longitude) + ext | |
lat_min <- min(df$latitude) - ext | |
lat_max <- max(df$latitude) + ext | |
# Make map --------------------------------------------------------------------- | |
## Grab satellite basemap | |
sat_map <- get_map(location = c(lon_min, lat_min, lon_max, lat_max), | |
maptype = "satellite", | |
source = "google") | |
## Make figure | |
ggmap(sat_map) + | |
geom_point(data = df, | |
aes(x = longitude, y = latitude, color = type), | |
size = 3) + | |
scale_color_manual(values = c("dodgerblue", "darkorange")) + | |
labs(color = "Treatment\nControl", | |
title = "Maps are cool") + | |
theme_void() + | |
theme(plot.title = element_text(face = "bold")) | |
## Export | |
ggsave(filename = "~/Desktop/map.png", | |
height = 5, | |
width = 5) |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment