---
title: "Introduction to cartographr"
output: 
  rmarkdown::html_vignette:
    self_contained: yes
    keep_md: yes
vignette: >
  %\VignetteIndexEntry{Introduction to cartographr}
  %\VignetteEngine{knitr::rmarkdown}
  %\VignetteEncoding{UTF-8}
---

```{r, include = FALSE}
knitr::opts_chunk$set(
  echo=TRUE,
  message=FALSE,
  warning=FALSE,
  collapse = TRUE,
  comment = "#>"
)
```

In this vignette, you will learn how to add new information to a map. Here, we retrieve a map of Manhattan, NYC. 


```{r setup}
library(cartographr)
library(dplyr)
library(ggplot2)
library(sf)
```

First, we load the locations of crimes in Manhattan. 


```{r load crime locations, echo=T, message=F, eval = F}
data("crime") 
data("soho_boundary")
```

# Convert longitude / latitude into a `sf`

To add the crime locations in the dataset to our map, we harness the `sf` (simple features) package, which includes a lot of useful tools for working with geo data. To this end, we convert the dataset into a `sf` object using latitude and longitude.  

```{r convert to sf, eval = F}
crime |> head()
```

This can be achieved with the function `sf::st_as_sf()` using the coordinates from the dataset. 

# Setup the map parameters

We have to provide `longitude`, `latitude` and `x_distance` (i.e., the width of the map in meters). Furthermore, we define the extend of the OSM data in meters in `get_osmdata()`. `y_distance` is calculated automatically using the output size aspect ratio. 

```{r define bbox, eval = F}
set_output_size("A4", orientation = "portrait")
osm <- get_osmdata(sf = soho_boundary)
```

# Plot the map

`plot_map()` generates a `ggplot2` object using the color theme set as parameter. That means that we can easily adjust the plot using `ggplot2` commands and also add new information to the map.

```{r create  map, message=FALSE, warning=FALSE, eval = F}
p <- osm |> 
  crop(soho_boundary) |> 
  plot_map(palette = "alphabet") +
  theme_infomap_barlow() + 
  
  # Add geom with crimes
  geom_point(data = crime,
             aes(x = longitude, y = latitude, shape = type), color="#A72424", size=2) + 
  
  # Set labels
  labs(title = "CRIME IN SOHO",
       shape = "TYPE")
```

Now we can plot the map by simply calling its print method implicity:

```{r plot the map, eval = F, fig.dim=c(5.81,8.3), fig.dpi = 72, out.width="100%"}
p
```

<p align="center">
  <img src='https://github.com/da-wi/cartographr/raw/develop/png/plot the map-1.png' width='80%'>
</p>

# Save map

`save_map()` can be used to store the print-ready plot object to the disk as a drawn object in `pdf` format. 

```{r save map, eval=F}
save_map(plot = p, filename = "ny_crime.pdf")
```

```{r save map as png, include = F, eval = F}
ggsave("png/plot the map-1.png", plot = p, width = 210, height= 297, units = "mm", dpi = 96)
```
