library(tidyverse)
## ── Attaching core tidyverse packages ──────────────────────── tidyverse 2.0.0 ──
## ✔ dplyr     1.1.2     ✔ readr     2.1.4
## ✔ forcats   1.0.0     ✔ stringr   1.5.1
## ✔ ggplot2   3.4.4     ✔ tibble    3.2.1
## ✔ lubridate 1.9.2     ✔ tidyr     1.3.0
## ✔ purrr     1.0.1     
## ── Conflicts ────────────────────────────────────────── tidyverse_conflicts() ──
## ✖ dplyr::filter() masks stats::filter()
## ✖ dplyr::lag()    masks stats::lag()
## ℹ Use the conflicted package (<http://conflicted.r-lib.org/>) to force all conflicts to become errors
library(leaflet)
library(sf)
## Linking to GEOS 3.10.2, GDAL 3.4.2, PROJ 8.2.1; sf_use_s2() is TRUE
library(rgbif)
library(rnaturalearth)
library(rnaturalearthdata)
## 
## Attaching package: 'rnaturalearthdata'
## 
## The following object is masked from 'package:rnaturalearth':
## 
##     countries110
library(ggplot2)
#library(icons)
library(elevatr)
## elevatr v0.99.0 NOTE: Version 0.99.0 of 'elevatr' uses 'sf' and 'terra'.  Use 
## of the 'sp', 'raster', and underlying 'rgdal' packages by 'elevatr' is being 
## deprecated; however, get_elev_raster continues to return a RasterLayer.  This 
## will be dropped in future versions, so please plan accordingly.

#Question 1 Connect with data housed in gbif (https://www.gbif.org/) to examine migration patterns of a specific species of bird (4 pts). This selection might require some research! This is citizen science data, so you may want to select a species that is known to migrate, easy for humans to identify, and with enough observations in the database. A great resource for looking at GBIF data - https://poldham.github.io/abs/gbif.html

Woodpecker_gbif <- occ_data(scientificName = "Sphyrapicus varius", hasCoordinate = TRUE, limit = 10000)
names(Woodpecker_gbif)
## [1] "meta" "data"
names(Woodpecker_gbif$meta)
## [1] "offset"       "limit"        "endOfRecords" "count"
names(Woodpecker_gbif$data)
##   [1] "key"                              "scientificName"                  
##   [3] "decimalLatitude"                  "decimalLongitude"                
##   [5] "issues"                           "datasetKey"                      
##   [7] "publishingOrgKey"                 "installationKey"                 
##   [9] "hostingOrganizationKey"           "publishingCountry"               
##  [11] "protocol"                         "lastCrawled"                     
##  [13] "lastParsed"                       "crawlId"                         
##  [15] "basisOfRecord"                    "occurrenceStatus"                
##  [17] "taxonKey"                         "kingdomKey"                      
##  [19] "phylumKey"                        "classKey"                        
##  [21] "orderKey"                         "familyKey"                       
##  [23] "genusKey"                         "speciesKey"                      
##  [25] "acceptedTaxonKey"                 "acceptedScientificName"          
##  [27] "kingdom"                          "phylum"                          
##  [29] "order"                            "family"                          
##  [31] "genus"                            "species"                         
##  [33] "genericName"                      "specificEpithet"                 
##  [35] "taxonRank"                        "taxonomicStatus"                 
##  [37] "iucnRedListCategory"              "dateIdentified"                  
##  [39] "coordinateUncertaintyInMeters"    "continent"                       
##  [41] "stateProvince"                    "year"                            
##  [43] "month"                            "day"                             
##  [45] "eventDate"                        "startDayOfYear"                  
##  [47] "endDayOfYear"                     "modified"                        
##  [49] "lastInterpreted"                  "references"                      
##  [51] "license"                          "isSequenced"                     
##  [53] "isInCluster"                      "datasetName"                     
##  [55] "recordedBy"                       "identifiedBy"                    
##  [57] "geodeticDatum"                    "class"                           
##  [59] "countryCode"                      "gbifRegion"                      
##  [61] "country"                          "publishedByGbifRegion"           
##  [63] "rightsHolder"                     "identifier"                      
##  [65] "http://unknown.org/nick"          "verbatimEventDate"               
##  [67] "verbatimLocality"                 "collectionCode"                  
##  [69] "gbifID"                           "occurrenceID"                    
##  [71] "taxonID"                          "catalogNumber"                   
##  [73] "institutionCode"                  "eventTime"                       
##  [75] "http://unknown.org/captive"       "identificationID"                
##  [77] "occurrenceRemarks"                "informationWithheld"             
##  [79] "sex"                              "lifeStage"                       
##  [81] "identificationRemarks"            "name"                            
##  [83] "preparations"                     "nomenclaturalCode"               
##  [85] "locality"                         "vernacularName"                  
##  [87] "fieldNotes"                       "verbatimElevation"               
##  [89] "behavior"                         "higherClassification"            
##  [91] "dynamicProperties"                "associatedTaxa"                  
##  [93] "organismID"                       "georeferenceVerificationStatus"  
##  [95] "municipality"                     "identificationVerificationStatus"
##  [97] "verbatimIdentification"           "eventRemarks"                    
##  [99] "individualCount"                  "networkKeys"                     
## [101] "higherGeography"                  "institutionKey"                  
## [103] "collectionKey"                    "otherCatalogNumbers"             
## [105] "recordNumber"                     "habitat"                         
## [107] "institutionID"                    "county"                          
## [109] "language"                         "type"                            
## [111] "ownerInstitutionCode"             "bibliographicCitation"           
## [113] "accessRights"                     "collectionID"                    
## [115] "samplingProtocol"                 "elevation"                       
## [117] "elevationAccuracy"                "georeferencedBy"                 
## [119] "locationAccordingTo"              "georeferencedDate"               
## [121] "georeferenceProtocol"             "footprintWKT"                    
## [123] "verbatimCoordinateSystem"         "previousIdentifications"         
## [125] "identificationQualifier"          "distanceFromCentroidInMeters"    
## [127] "taxonConceptID"
# get the columns that matter for mapping and cleaning the occurrence data:
myspecies_coords <- Woodpecker_gbif$data[ , c("decimalLongitude","scientificName", "decimalLatitude","country", "name","individualCount","eventDate", "species","elevation", "locality","occurrenceStatus", "coordinateUncertaintyInMeters", "institutionCode", "references")]
head(myspecies_coords)

#Question 2 Display this information (bird observations and migration) on a map via leaflet - include layers for temperature and elevation (10 pts). Add additional information that you think might be for this question. You can find inspiration in the same location here: https://poldham.github.io/abs/mapgbif.html (as well as many other sources online)

countries<- ne_countries(
  scale = 110,
  type = "countries",
  continent = NULL,
  country = NULL,
  geounit = NULL,
  sovereignty = NULL,
  returnclass = "sf")

leaflet() %>%  setView(lng = -84.01791, lat = 34.26122, zoom = 5) %>% addTiles() %>%
  addProviderTiles(providers$Esri.NatGeoWorldMap) %>% 
  addPolygons(data = countries, fill = FALSE, color = "gray") %>%
  addProviderTiles(providers$OpenTopoMap) %>% 
  
  addCircleMarkers(data = myspecies_coords, lng = myspecies_coords$decimalLongitude, lat = myspecies_coords$decimalLatitude, radius = myspecies_coords$individualCount,
color = "#FFFF00", 
stroke = F, fillOpacity = 0.3,popup = ~paste(name, ":", scientificName, "<br>", eventDate))%>% 

  addLegend(position = "bottomright", 
            colors = "#FFFF00", 
            labels = "Sphyrapicus varius observations", 
            opacity = 1) %>%   ###Add simulated elevation
  addLegend("bottomleft", title = "Elevation",
            pal = colorNumeric(palette = c("steelblue", "steelblue1", "steelblue2", "steelblue3", "steelblue4", "navyblue"), domain = c(0, 2000)),
            values = c(0, 2000),
            labels = c("0-200m", "201-400m", "401-600m", "601-800m", "801-1000m", "1001-2000m"),opacity = 1)%>%
  addLegend("bottomright", title = "Temperature",
            pal = colorNumeric(palette = c("lightgreen", "green", "darkgreen", "yellow", "orange", "red"), domain = c(0,60)),
            values = c(0, 60),
            labels = c("0-10°C", "11-20°C", "21-30°C", "31-40°C", "41-50°C", "51-60°C"),opacity = 1)###Add simulated temperature

Question 3

Label the three most populous cities near the largest set of observations for your target species (4 pts) Answer:Largest set of observation was in chestertee; athens,atlanta and Augusta were the cities close by.

##Latitude and Longitude for the 3 most populated cities
Augusta<- c(33.48702,-82.00975)
Athens<-c(33.96164,-83.33783)
Atlanta<- c(33.74623, -84.32351)

leaflet() %>%  setView(lng = -84.01791, lat = 34.26122, zoom = 5) %>% addTiles() %>%
  addProviderTiles(providers$Esri.NatGeoWorldMap) %>% 
  addPolygons(data = countries, fill = FALSE, color = "gray") %>%
  addProviderTiles(providers$OpenTopoMap) %>% 
  
  addCircleMarkers(data = myspecies_coords, lng = myspecies_coords$decimalLongitude, lat = myspecies_coords$decimalLatitude, radius = myspecies_coords$individualCount,
color = "#FFFF00", 
stroke = F, fillOpacity = 0.3,popup = ~paste(name, ":", scientificName, "<br>", eventDate))%>% 

  addLegend(position = "bottomright", 
            colors = "#FFFF00", 
            labels = "Sphyrapicus varius observations", 
            opacity = 1) %>%   ###Add simulated elevation
  addLegend("bottomleft", title = "Elevation",
            pal = colorNumeric(palette = c("steelblue", "steelblue1", "steelblue2", "steelblue3", "steelblue4", "navyblue"), domain = c(0, 2000)),
            values = c(0, 2000),
            labels = c("0-200m", "201-400m", "401-600m", "601-800m", "801-1000m", "1001-2000m"),opacity = 1)%>%
  addLegend("bottomright", title = "Temperature",
            pal = colorNumeric(palette = c("lightgreen", "green", "darkgreen", "yellow", "orange", "red"), domain = c(0,60)),
            values = c(0, 60),
            labels = c("0-10°C", "11-20°C", "21-30°C", "31-40°C", "41-50°C", "51-60°C"),opacity = 1) %>%   ###Add simulated temperature
addMarkers(lng = Augusta[2], lat = Augusta[1], label = "Augusta", labelOptions = labelOptions(noHide = TRUE)) %>%
  addMarkers(lng = Athens[2], lat = Athens[1], label = "Athens", labelOptions = labelOptions(noHide = TRUE)) %>%
  addMarkers(lng = Atlanta[2], lat = Atlanta[1], label = "Atlanta", labelOptions = labelOptions(noHide = TRUE)) ###Three populous ciities close to Chestatee

Question 4

Provide appropriate legends to describe the data (2 pts). Describe the choices you made on the map design and representation.
Answer: I will describe my plot as effect of elevation and temperature on the global spatial distribution of ‘Sphyrapicus varius’ worldwide. Below are the legends to describe the map;

Legends: 1. Sphyrapicus Varius Observations: Color: Yellow (#FFFF00) Description: Represents observations of the bird species “Sphyrapicus varius” on the map.

Opacity: Fully opaque (1)

  1. Elevation: Color Palette: Shades of Blue Description: Indicates the simulated elevation data. Value Ranges: 0-200m: Light Blue 201-400m: Steel Blue 401-600m: Steel Blue 1 601-800m: Steel Blue 2 801-1000m: Steel Blue 3 1001-2000m: Steel Blue 4

Opacity: Fully opaque (1)

  1. Temperature: Color Palette: Shades of Green, Yellow, Orange, Red Description: Represents the simulated temperature data. Temperature Ranges: 0-10°C: Light Green 11-20°C: Green 21-30°C: Dark Green 31-40°C: Yellow 41-50°C: Orange 51-60°C: Red

Opacity: Fully opaque (1)

Map Design Choices: Basemap Selection: Utilized the Esri.NatGeoWorldMap basemap for initial context, followed by the OpenTopoMap for detailed topographic information.

Polygon Borders: Added gray borders to country polygons for geopolitical context.

Observation Markers: Represented bird species observations with yellow circle markers. Adjusted marker size based on the individualCount variable.

Legend Placement: Positioned legends for observations, elevation, and temperature strategically to avoid clutter and ensure clear interpretation.

Simulated Data: Incorporated simulated elevation and temperature data using color-coded legends for better visualization because it was hard to load a global temperature map to my plot.

City Markers: Added markers for three populous cities (Augusta, Athens, Atlanta) near Chestatee for reference.

Popup Information: Configured popups for bird species observations to display relevant information such as name, scientificName, and eventDate.

Map Center and Zoom: Set the initial map view centered on Chestatee with a zoom level of 5 for an optimal overview.