knitr::opts_chunk$set(echo = TRUE)

library(leaflet)
library(rgbif)
library(dplyr)
library(rnaturalearth)
library(rnaturalearthdata)
library(ggplot2)
library(icons)
library(elevatr)
library(sf)

states <- ne_states(country = "united states of america", returnclass = "sf")

# GBIF
hirundo_observations <- occ_search(
  scientificName = "Hirundo rustica",
  country = "US",
  hasCoordinate = TRUE,
  limit = 2000
)$data

# GBIF
hirundo_observations_winter <- occ_search(
  scientificName = "Hirundo rustica",
  country = "MX",
  hasCoordinate = TRUE,
  limit = 2000
)$data

# GBIF
hirundo_observations_winter <- occ_search(
  scientificName = "Hirundo rustica",
  country = "MX",
  hasCoordinate = TRUE,
  limit = 2000
)$data


map <- leaflet() %>% setView(lng = -79, lat = 37.8, zoom = 5) %>% addTiles() %>%
  addProviderTiles(providers$Esri.NatGeoWorldMap) %>% 
  addPolygons(data = states, fill = FALSE, color = "gray") %>% 
  addProviderTiles(providers$OpenTopoMap) %>%
 
  addCircleMarkers(data = hirundo_observations, 
                   ~decimalLongitude, ~decimalLatitude, 
                   color = "#FFB6C1", fillOpacity = 1, radius = 3, 
                   popup = ~paste(name, ":", scientificName, "<br>", eventDate),
                   group = "Hirundo rustica observations") %>%
  addCircleMarkers(data = hirundo_observations_winter, 
                   ~decimalLongitude, ~decimalLatitude, 
                   color = "blue", fillOpacity = 1, radius = 3, 
                   popup = ~paste(name, ":", scientificName, "<br>", eventDate),
                   group = "Hirundo rustica winter observations") %>%
  
  addLayersControl(
    overlayGroups = c("Hirundo rustica observations", "Hirundo rustica winter observations"),
    options = layersControlOptions(collapsed = FALSE)) %>%
  addLegend(position = "bottomright", 
            colors = c("#FFB6C1", "blue"), 
            labels = c("Hirundo rustica observations", "Hirundo rustica winter observations"), 
            opacity = 1) %>%
  addLegend("bottomleft", title = "Elevation",
            pal = colorNumeric(palette = c("lightgreen", "green", "darkgreen", "yellow", "orange", "red"), domain = c(0, 2000)),
            values = c(0, 2000),
            labels = c("0-200m", "201-400m", "401-600m", "601-800m", "801-1000m", "1001-2000m"),opacity = 1)

map