library(leaflet)

library(sf)
## Linking to GEOS 3.13.1, GDAL 3.11.0, PROJ 9.6.0; sf_use_s2() is TRUE
library(tidyverse)
## ── Attaching core tidyverse packages ──────────────────────── tidyverse 2.0.0 ──
## ✔ dplyr     1.1.4     ✔ readr     2.1.5
## ✔ forcats   1.0.1     ✔ stringr   1.5.2
## ✔ ggplot2   4.0.0     ✔ tibble    3.3.0
## ✔ lubridate 1.9.4     ✔ tidyr     1.3.1
## ✔ purrr     1.1.0
## ── 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(tigris) #USABoundaries can't be download so i used tigris instead.
## To enable caching of data, set `options(tigris_use_cache = TRUE)`
## in your R script or .Rprofile.
leaflet() |>
  addTiles() |>
  addMarkers(lng=-105.0848, lat=40.5729, popup="CSU")
(leaflet() |> 
    setView(lng=-105.0848, lat=40.5729, zoom = 12) |> 
    addTiles()) 
length(providers)
## [1] 233
names(providers) |> 
  head()
## [1] "OpenStreetMap"        "OpenStreetMap.Mapnik" "OpenStreetMap.DE"    
## [4] "OpenStreetMap.CH"     "OpenStreetMap.France" "OpenStreetMap.HOT"
leaflet() |> 
  setView(lng=-105.0848, lat=40.5729, zoom = 12) |> 
  addProviderTiles(providers$CartoDB)
leaflet() |> 
  setView(lng=-105.0848, lat=40.5729, zoom = 12) |> 
  addProviderTiles(providers$Esri.WorldImagery)
starbucks <- read_csv('C:/Users/ddtmd/Desktop/2025 Fall/GEOG588/Lab4/directory.csv') |>
  filter(City %in% c("Fort Collins", "Loveland"),
         `State/Province` == "CO") |>
  st_as_sf(coords = c("Longitude", "Latitude"), crs = 4326) |>
  select(store_name = `Store Name`,
         phone = `Phone Number`,
         address = `Street Address`,
         city = City,
         brand = Brand)
## Rows: 25600 Columns: 13
## ── Column specification ────────────────────────────────────────────────────────
## Delimiter: ","
## chr (11): Brand, Store Number, Store Name, Ownership Type, Street Address, C...
## dbl  (2): Longitude, Latitude
## 
## ℹ Use `spec()` to retrieve the full column specification for this data.
## ℹ Specify the column types or set `show_col_types = FALSE` to quiet this message.
leaflet() |> 
  addProviderTiles(providers$CartoDB) |> 
  addMarkers(data = starbucks, popup = ~store_name, label = ~city)
icons = awesomeIcons(icon = 'coffee', markerColor = "green", library = 'fa', spin = TRUE)

leaflet(data = starbucks) |> addProviderTiles(providers$CartoDB) |> 
  addAwesomeMarkers(icon = icons, popup = ~store_name)
starbucks = starbucks |> 
  mutate(url = paste0('https://www.google.com/maps/place/',
                      gsub(" ", "+", address), "+",
                      gsub(" ", "+", city)))

pop = paste0('<a href=', starbucks$url, '>', starbucks$store_name, "</a>")
head(pop)
## [1] "<a href=https://www.google.com/maps/place/4609+S+Timberline+Rd,+Unit+A101+Fort+Collins>Harmony & Timberline-Fort Collins</a>"
## [2] "<a href=https://www.google.com/maps/place/460A+South+College+Fort+Collins>Safeway-Fort Collins #1071</a>"                    
## [3] "<a href=https://www.google.com/maps/place/2601+S+Lemay,+Ste+130+Fort+Collins>Scotch Pines</a>"                               
## [4] "<a href=https://www.google.com/maps/place/2602+S+Timberline+Rd+Fort+Collins>King Soopers-Fort Collins #97</a>"               
## [5] "<a href=https://www.google.com/maps/place/2160+W+Drake+Rd,+Unit+6+Fort+Collins>Safeway-Fort Collins #2913</a>"               
## [6] "<a href=https://www.google.com/maps/place/250+E.+Harmony+Road+Fort+Collins>Harmony & JFK</a>"
leaflet(data = starbucks) |>
  addProviderTiles(providers$CartoDB) |> 
  addAwesomeMarkers(icon = icons, 
                    label = ~address, popup = pop)
leaflet(data = starbucks) |>
  addProviderTiles(providers$CartoDB) |> 
  addCircleMarkers(label = ~address, popup = pop)
all_co = read_csv('C:/Users/ddtmd/Desktop/2025 Fall/GEOG588/Lab4/directory.csv') |> 
  filter(!is.na(Latitude)) |> 
  st_as_sf(coords = c("Longitude", "Latitude"), crs = 4326) 
## Rows: 25600 Columns: 13
## ── Column specification ────────────────────────────────────────────────────────
## Delimiter: ","
## chr (11): Brand, Store Number, Store Name, Ownership Type, Street Address, C...
## dbl  (2): Longitude, Latitude
## 
## ℹ Use `spec()` to retrieve the full column specification for this data.
## ℹ Specify the column types or set `show_col_types = FALSE` to quiet this message.
leaflet(data = all_co) |> 
  addProviderTiles(providers$CartoDB) |> 
  addMarkers(clusterOptions = markerClusterOptions())
# ?colorFactor

# Create a palette that maps factor levels to colors
pal <- colorFactor(c("darkgreen", "navy"), domain = c("Goleta", "Santa Barbara"))

leaflet(data = starbucks) |> addProviderTiles(providers$CartoDB) |> 
  addCircleMarkers(color = ~pal(city), fillOpacity = .5, stroke = FALSE)
## Warning in pal(city): Some values were outside the color scale and will be
## treated as NA
## Warning in pal(city): Some values were outside the color scale and will be
## treated as NA
# --- state polygons (lower 48 + DC) ---
states <- tigris::states(cb = TRUE, year = 2023, progress_bar = FALSE) |>
  filter(!STUSPS %in% c("AK", "HI", "PR")) |>
  transmute(state = NAME, stusps = STUSPS, geometry)  # keep only what we need

# --- latest COVID data ---
covid <- read_csv(
  "https://raw.githubusercontent.com/nytimes/covid-19-data/master/live/us-states.csv",
  show_col_types = FALSE
) |>
  filter(date == max(date, na.rm = TRUE)) |>
  select(state, cases, deaths)

# --- join + map ---
states_covid <- states |> left_join(covid, by = "state")

pal <- colorBin("YlOrRd", domain = states_covid$cases, bins = 7, na.color = "#cccccc")

leaflet(states_covid) |>
  addProviderTiles("CartoDB.Positron") |>
  addPolygons(
    weight = 1, color = "#555555",
    fillOpacity = 0.7,
    fillColor = ~pal(cases),
    popup = ~paste0(
      "<b>", state, "</b><br>",
      "Cases: ", formatC(cases, format = "d", big.mark = ","), "<br>",
      "Deaths: ", formatC(deaths, format = "d", big.mark = ",")
    )
  ) |>
  addLegend("bottomright", pal = pal, values = ~cases,
            title = "Cases", opacity = 0.7)
## Warning: sf layer has inconsistent datum (+proj=longlat +datum=NAD83 +no_defs).
## Need '+proj=longlat +datum=WGS84'
# Safer popup (quoted + URL-encoded)
starbucks <- starbucks |>
  mutate(url = utils::URLencode(
    paste0("https://www.google.com/maps/place/", address, ", ", city),
    reserved = TRUE
  ))

# Color palette from your data (Fort Collins / Loveland)
pal_pts <- colorFactor("Set2", domain = unique(starbucks$city))

# Map with labels, popups, AND a legend ✅
leaflet(starbucks) |>
  addProviderTiles("CartoDB.Positron") |>
  addCircleMarkers(
    label = ~address,
    popup = pop,
    color = ~pal_pts(city),
    fillOpacity = 0.6,
    stroke = FALSE
  ) |>
  addLegend(
    position = "bottomleft",
    pal = pal_pts,
    values = ~city,
    title = "City",
    opacity = 0.8
  )