Putnam-Lab / Lab_Management

13 stars 7 forks source link

Help with Google API key generation for making maps in R #86

Closed daniellembecker closed 4 days ago

daniellembecker commented 2 months ago

Just wondering if anyone has a valid Google API key for making maps in R?

I previously had one during my masters but it is no longer active and I tried to activate a new one following these instructions but I am still running into an error in my code that says:

Create a dataframe with site coordinates

sites <- data.frame( Site = c("Fort Weatherill", "King's Beach"), Latitude = c(41.477, 41.452), # Adjusted approximate values for the sites Longitude = c(-71.364, -71.326) # Adjusted approximate values for the sites )

Get map of the larger area

larger_map <- get_map(location = "NarrBay", zoom = 10, source = "google", api_key = AIzaSyAekKwRATXAivmwiWh24Bz_oZWSQtbw-po)

ℹ <https://maps.googleapis.com/maps/api/staticmap?center=NarrBay&zoom=10&size=640x640&scale=2&maptype=terrain&language=en-EN&key=xxx> Error in get_googlemap(center = location, zoom = zoom, maptype = maptype, : HTTP 400 Bad Request The Google Maps Platform server rejected your request. You must enable Billing on the Google Cloud Project at https://console.cloud.google.com/project/_/billing/enable Learn more at https://developers.google.com/maps/gmp-get-started

JillAshey commented 2 months ago

I've never used a google API key but I used this code to make a map for my Astrangia review paper

This script creates a map of Astrangia distribution based on data collected from OBIS and xxxxx. 

## Load packages 
```{r setup, include=FALSE}
knitr::opts_chunk$set(echo = TRUE)

#install.packages(c("cowplot", "googleway", "ggplot2", "ggrepel", "ggspatial", "libwgeom", "sf", "rnaturalearth", "rnaturalearthdata"))

#library("cowplot")
#library("googleway")
#library("ggrepel")
#library("ggspatial")
#library("libwgeom")
library("sf")
library("rnaturalearth")
library("rnaturalearthdata")
library("tidyverse")

Load and subset data

## data from OBIS
obis <- read.csv("data/OBIS/Occurrence.csv")
obis <- obis %>%
  select(id, decimallongitude, decimallatitude, date_year, scientificname, originalscientificname, institutioncode, sst, basisofrecord, occurrencestatus, waterbody, country, stateprovince) %>% # select specific columns of interest
  drop_na(decimallongitude) %>% # remove data that does not have longitude values
  drop_na(decimallatitude) # remove data that does not have latitude values

## data from GBIF
gbif <- read.delim("data/GBIF/occurrence.txt")
gbif <- gbif %>%
  select(gbifID, rightsHolder, basisOfRecord, occurrenceStatus, year, continent, countryCode, stateProvince, decimalLongitude, decimalLatitude, scientificName, acceptedScientificName, collectionCode, datasetName) %>% # select specific columns of interest
  drop_na(decimalLongitude) %>% # remove data that does not have longitude values
  drop_na(decimalLatitude) # remove data that does not have latitude values

Examine where the data came from & how the data was collected

## OBIS
unique(obis$institutioncode)
#  [1] "WoodsHoleBioSurvey"                             "HRI"                                            ""                                              
#  [4] "Smithsonian Environmental Research Center"      "SMCC"                                           "TCWC"                                          
#  [7] "USNM"                                           "NOAA, NMFS, Northeast Fisheries Science Center" "EMAP_NCA"                                      
# [10] "HEX"                                            "OGL"                                            "UF"    

unique(obis$basisofrecord)
# [1] "HumanObservation"  "PreservedSpecimen"

## GBIF
unique(gbif$datasetName)
# [1] "iNaturalist research-grade observations"     ""                                            "NMNH Extant Biology"                        
# [4] "NMNH Material Samples (USNM)"                "Ocean Genome Legacy Collection"              "NCSM Non-molluscan Invertebrates Collection"

unique(gbif$basisOfRecord)
# [1] "HUMAN_OBSERVATION"  "PRESERVED_SPECIMEN" "FOSSIL_SPECIMEN"    "MATERIAL_SAMPLE"   

I am only interested in mapping the points that came from 'human observations'. Preserved samples or fossil specimans might skew the data depending on where they were collected.

Filter by Human Observation only

obis_human <- obis %>%
  filter(basisofrecord == "HumanObservation")
unique(obis_human$institutioncode)

gbif_human <- gbif %>%
  filter(basisOfRecord == "HUMAN_OBSERVATION")
unique(gbif_human$datasetName)

Combine datasets

obis_human$Source <- "OBIS"
obis_human <- obis_human %>%
  select(decimallongitude, decimallatitude, date_year, basisofrecord, Source)

gbif_human$Source <- "GBIF"
gbif_human <- gbif_human %>%
  select(basisOfRecord, year, decimalLongitude, decimalLatitude, Source) %>%
  relocate(decimalLongitude, decimalLatitude, year, basisOfRecord, Source) %>%
  rename("decimallongitude" = "decimalLongitude", "decimallatitude" = "decimalLatitude", "date_year" = "year", "basisofrecord" = "basisOfRecord")

all <- rbind(obis_human, gbif_human)

Plot individual sources

world <- ne_countries(scale = "medium", returnclass = "sf")

## OBIS
obis_plot <- ggplot(data = world) +
  geom_sf() +
  geom_point(data = obis_human, aes(x = decimallongitude, y = decimallatitude, shape = Source, color = Source), size = 2, color = "black") +
  coord_sf(xlim = c(-100, -55), ylim = c(13, 45), expand = FALSE) +
  ylab("Latitude") +
  xlab("Longitude") +
  theme_linedraw() +
  theme(legend.position = "none")

obis_plot + annotate(geom = "text", x = -90, y = 37, label = "North America") +
  annotate(geom = "text", x = -65, y = 28, label = "Atlantic Ocean")

## GBIF
gbif_plot <- ggplot(data = world) +
  geom_sf() +
  geom_point(data = gbif_human, aes(x = decimallongitude, y = decimallatitude, shape = Source, color = Source), size = 2, color = "black") +
  coord_sf(xlim = c(-100, -55), ylim = c(13, 45), expand = FALSE) +
  ylab("Latitude") +
  xlab("Longitude") +
  #geom_text(x = -90, y = 37, label = "test") +
  theme_linedraw() +
  theme(legend.position = "none")

gbif_plot + annotate(geom = "text", x = -90, y = 37, label = "North America") +
  annotate(geom = "text", x = -65, y = 28, label = "Atlantic Ocean")
daniellembecker commented 2 months ago

Thank you! I also couldn't get the key to work but the packages you suggested allowed me to make some maps too, thank you!

Use this script to use cleaned data and make plots for RI kelp data manuscript

Load libraries

library(plyr)
library(dplyr)
library(tigris)
library(car)
library(MuMIn)
library(lmerTest)
library(tidyverse)
library(lme4)
library(broom.mixed)
library(ggmap)
library(lubridate)
library(ggplot2)
library(patchwork)
library(broom)
library(ggspatial)
if ("ggsn" %in% rownames(installed.packages()) == 'FALSE') BiocManager::install("ggsn")
library(ggsn)
library(sf)
library(rnaturalearth)
library(rnaturalearthdata)
library(ggspatial)

load cleaned dataframes

# Set your directory path
directory <- "output/cleaned_data/"

# List files in the directory
files <- list.files(directory)

# Initialize an empty list to store data frames
data_frames <- list()

# Loop through each file
for (file in files) {
    # Read the file into a data frame
    # Adjust the read function according to your file type (e.g., read.csv, read.table)
    # Specify other parameters as needed (e.g., header = TRUE)
    file_path <- file.path(directory, file)
    df_name <- gsub("\\..*", "", file)  # Extract file name without extension
    assign(df_name, read.csv(file_path, stringsAsFactors = FALSE))
}

# Now, each file is a separate data frame with its own variable name

Figure 1: organize data and make study site map of a) larger RI and NarrBay with Ft Weatherill and Kings Beach areas in boxes; b) zoom in of the Ft Weatherill box with specific transects as dots; c) zoom in of the Kings Beach box with specific transects as dots.

# Create a dataframe with site coordinates
sites <- data.frame(
  Site = c("Fort Weatherill", "King's Beach"),
  Latitude = c(41.477, 41.452),  # Adjusted approximate values for the sites
  Longitude = c(-71.364, -71.326) # Adjusted approximate values for the sites
)

# Convert sites dataframe to an sf object
sites_sf <- st_as_sf(sites, coords = c("Longitude", "Latitude"), crs = 4326)

# Get Rhode Island state boundaries
ri_state <- states(cb = TRUE) %>% 
  filter(STUSPS == "RI") %>%
  st_transform(crs = 4326)

# Define the larger rectangle size (adjust as needed)
rect_size <- 0.02 

# Function to create rectangles around each site
create_rectangle <- function(site, rect_size) {
  lon <- st_coordinates(site)[1]
  lat <- st_coordinates(site)[2]
  st_as_sf(st_sfc(st_polygon(list(rbind(
    c(lon - rect_size, lat - rect_size), 
    c(lon - rect_size, lat + rect_size), 
    c(lon + rect_size, lat + rect_size), 
    c(lon + rect_size, lat - rect_size), 
    c(lon - rect_size, lat - rect_size)
  )))), crs = st_crs(site))
}

# Apply the create_rectangle function to each site
site_rectangles <- lapply(st_geometry(sites_sf), function(site) {
  create_rectangle(site, rect_size)
})

# Combine all rectangles into one sf object
site_rectangles <- do.call(rbind, site_rectangles)
st_crs(site_rectangles) <- st_crs(sites_sf) # Ensure CRS is set for combined rectangles

# Define label data
labels <- data.frame(
  name = c("Narragansett\nBay", "Atlantic\nOcean"),
  lat = c(41.6, 41.3),
  lon = c(-71.35, -71.2)
)

# Plot
panelA <- ggplot() +
  geom_sf(data = ri_state, fill = "lightgray") + # State boundaries
  geom_sf(data = site_rectangles, color = "red2", fill = NA, size = 2) + # Add rectangles around sites
  #geom_sf(data = sites_sf, color = "blue", size = 3) + # Add site points for reference
  geom_text(data = labels, aes(x = lon, y = lat, label = name), size = 5, color = "black") + # Add labels
  coord_sf(xlim = c(-72, -71.0), ylim = c(41.1, 42.1), expand = FALSE) + # Zoom level
  annotation_scale(location = "bl", width_hint = 0.5) +
  annotation_north_arrow(location = "bl", which_north = "true", 
                         pad_x = unit(1.1, "in"), pad_y = unit(0.4, "in"),
                         style = north_arrow_fancy_orienteering) +
  theme_classic() # Remove axes and background

panelA

# Save the plot to a file
ggsave("output/figures/figure_1A.png", plot = panelA, width = 8, height = 6)

# Filter transect data by site
transect_fw <- filter(site, Site == "Fort Wetherill")

# Define label data
labels <- data.frame(
  name = c("Fort\nWetherill"),
  lat = c(41.485),
  lon = c(-71.368)
)

# Plot
panelB <- ggplot() +
  geom_sf(data = ri_state, fill = "lightgray") + # State boundaries
  geom_point(data = transect_fw,
             aes(x = Start.Longitude, y = Start.Latitude),
            color = "red", size = 3) + # Add start points of transects
  annotation_scale(location = "bl", width_hint = 0.5) +
  annotation_north_arrow(location = "bl", which_north = "true", 
                         pad_x = unit(1.5, "in"), pad_y = unit(0.2, "in"),
                         style = north_arrow_fancy_orienteering) +
    geom_text(data = labels, aes(x = lon, y = lat, label = name), size = 5, color = "black") + # Add labels
  theme_classic() + # Remove axes and background
  xlim(c(-71.45, -71.3)) + # Set longitude range
  ylim(c(41.42, 41.5))   # Set latitude range

panelB

# Save the plot to a file
ggsave("output/figures/figure_1B.png", plot = panelB, width = 8, height = 6)