```{r packages, echo = FALSE, warning = FALSE, message = FALSE}
knitr::opts_chunk$set(eval = TRUE)
options(dplyr.print_max = 12)
```

Work code - see the slides for the final code. This is broken because it's based on rnaturalearth::world, not spData::world.

cf. 
- https://chiajung-yeh.github.io/Spatial-Analysis/

```{r}
library(tidyverse)
library(sf)
# library(spData)
```

`world` is an R list that represents an simple-feature (sf) collection of 241 countries, 63 fields per country. Note:

- Bounding box of most of the globe: -180&ndash;180 longitude and -89.99&ndash;83.59 latitude
- CRS: [WGS84 aka. EPSG:4326](https://en.wikipedia.org/wiki/World_Geodetic_System#WGS84). This one, represented using a complicated string (PROJ4), has three basic components:
  - Datum: commonly WGS coordinates
  - Projection: This one is `longlat` which isn't a projection - geom_sf must have a default.
  - Additional Parameters: e.g., center-of-map ?? (for Albers?)
- Geometry: MULTIPOLYGON geometry specified using:
  - Well-Known Text (WKT) format (i.e., points, linestrings, polygons, and multi-* versions of all three)
  - Coordinates: x (longitude); y (latitude) (i.e., `longlat`). Note that these are angular because the specify a location on the Earth's sphere (see [WGS84 reference frame](https://en.wikipedia.org/wiki/World_Geodetic_System#/media/File:WGS_84_reference_frame_(vector_graphic).svg).
  
`ggplot` & `sf` work together to plot this data easily.

```{r}
world

world %>%
 ggplot() +
   geom_sf()
```

Here's some of the data for Afghanistan. Note that R list represents this in columns, with separate/parallel lists for: name, geometry, &hellip;

```{r}
country_index <- 2  # Afghanistan

world$name[country_index]
world$region_wb[country_index]
world$geometry[country_index]

world$geometry[country_index] %>%
 ggplot() +
   geom_sf() +
   geom_sf_text(aes(label = world$formal_en[country_index]))
```

Because the Earth is not flat, all geospatial data needs to be projected onto a 2D surface to be visualized as a *map*. See the [orange peel](https://datacarpentry.org/organization-geospatial/03-crs/index.html) analogy.

Because the CRS for the plots above is `longlat`, which is unprojected, ggplot/geom_sf are using a default projection that I don't know. The manual says: "The coordinate reference system (CRS) into which all data should be projected before plotting. If not specified, will use the CRS defined in the first sf layer of the plot."

```{r}
world %>%
  ggplot() +
    geom_sf() +
    coord_sf(crs = 4326) +  # The default, whatever it is
    ggtitle("WGS 84 - WGS84 - World Geodetic System 1984, used in GPS")
    # cowplot::theme_minimal_grid()
```


```{r}
world %>%
  ggplot() +
    # ggspatial::layer_spatial(data = world)+
    coord_sf(crs = 3395) +
    ggtitle("WGS 84 / World Mercator")+
    cowplot::theme_minimal_grid()
```

