## Why leaflet?
It's one of the openly used openscript libraries for making interactive maps and used by many to publish maps. This R package helps bring the same functionality to R, and makes it easy to integrate and control Leaflet maps in R. 

* Create maps right from the R console or RStudio 

* Embed maps in R Markdown documents and Shiny apps 

* Easily render spatial objects from the sp or sf packages, or data frames with latitude/longitude columns

#### Packages to Install
To install this R package, run this command at your R prompt:
```
install.packages("leaflet") # main package 

install.packages("maps")

```

####Basic Usage
You create a Leaflet map with these basic steps:

1. Create a map widget by calling leaflet().

2. Add layers (i.e., features) to the map by using layer functions (e.g. addTiles, addMarkers,  addPolygons) to modify the map widget.

3. Repeat step 2 as desired.

4. Print the map widget to display it.

###Basic example
To get a sense of the package, lets start out with an example for its usage:

```{r}
library(leaflet)

m <- leaflet() %>%
  addTiles() %>%  # Add default OpenStreetMap map tiles
  addMarkers(lng=-73.2013, lat=44.4783, popup="Waterman building, UVM") # Decimal degrees - latitude and longitude, the values are bounded by ±90° and ±180° respectively.

m  # Print the map

```
Note that using the print() to print the output in Rmarkdown does not give the actual output.

###Map views
```{r}

require(leaflet)
m <- leaflet() %>% addTiles()

#setView()
m %>% setView(-73.2, 44.48, zoom = 16) #Restricts the map view to the given bounds
  
#fitBounds()
m %>% fitBounds(-73.2, 44.48,-73.1, 44.49) #Set the bounds of a map
```

Other examples:
```
#setMaxBounds()
m %>%
  setMaxBounds(-73.2, 44.48,-73.1, 44.49) #Restricts the map view to the given bounds
  
#clearBounds()
m %>% clearBounds()  # world view

```

###Data Object

Both leaflet() and map layer function has an optional parameter that is designed to receive data in one of the several forms:

a. From base R: from matrix or data frame with lat/long columns

b.  From `sp` packages

c. From the `maps package`

Example 1. From Base R

```{r}
df = data.frame(Lat = 1:10, Long = rnorm(10))
leaflet(df) %>% addTiles() %>% addCircles()
```

Example 2. From the `maps package`
```{r}
require("maps")
library(maps)
mapStates = map("state", fill = TRUE, plot = FALSE)

leaflet(data = mapStates) %>% addTiles() %>%
  addPolygons(fillColor = topo.colors(10, alpha = NULL), stroke = FALSE)
```


###Basemaps

The easiest way to add tiles is by calling addTiles() with no arguments; by default, OpenStreetMap tiles are used.

```{r}

m <- leaflet() %>% setView(lng=-73.2013454, lat=44.4783732, zoom = 12)
m %>% addTiles() #default:OpenStreetMap
```

####A) Third party tiles
Popular free third-party basemaps can be added using the `addProviderTiles()` function, which is implemented using the leaflet-providers plugin.
The list of third party map providers can also be obtained by running the below code:
```{r}
head(names(providers))
```

#### Some examples of the maps available in leaflet are shown below:
##### Open TopoMap:

```{r, echo=FALSE}
m %>% addProviderTiles(providers$OpenTopoMap)
```

##### Stamen Toner:

```{r, echo=FALSE}
m %>% addProviderTiles(providers$Stamen.Toner)
```

##### ESRI NatGeoWorldMap:

```{r, echo=FALSE}
m %>% addProviderTiles(providers$Esri.NatGeoWorldMap)
```


####B) Stacking base maps
With the adjustent in opacity, different base maps can be stacked on top of each other. This helps in augmenting the deatails in a given map. You might need to work a bit all the map types to get a sense of which all combinations works best. The example below uses the NatGeoWorldMap from ESRI and overlay it with the contrasting map lines and names of Stamen Toner.

```{r}

m %>% addProviderTiles(providers$Esri.NatGeoWorldMap) %>%
  addProviderTiles(providers$Stamen.TonerLines,
                   options = providerTileOptions(opacity = 0.75)) %>%
  addProviderTiles(providers$Stamen.TonerLabels)


```


####Shape and Polygons

Circles:
The circle size is not based on pixel, so even when you zoom in or zoom out, it does not vary in shape. An example of this is given below.

```{r}
cities <- read.csv(textConnection("
City,Lat,Long,Pop
Boston,42.3601,-71.0589,645966
Hartford,41.7627,-72.6743,125017
New York City,40.7127,-74.0059,8406000
Philadelphia,39.9500,-75.1667,1553000
Pittsburgh,40.4397,-79.9764,305841
Providence,41.8236,-71.4222,177994
"))

leaflet(cities) %>% addTiles() %>%
  addCircles(lng = ~Long, lat = ~Lat, weight = 1,
    radius = ~sqrt(Pop) * 50, popup = ~City
  )

```

Rectangles:
Similar concepts apply here, but instead of using a data set to set the size, you need to define the four corners of the rectangle with lat and long values.

```{r}
leaflet() %>% addTiles() %>%
  addRectangles(
    lng1=-118.456554, lat1=34.078039,
    lng2=-118.436383, lat2=34.062717,
    fillColor = "red"
  )
```

###Markers
It's always useful to mark your datapoints on a map to observe the spatial distribution of the dataset.

```{r}
data(quakes) #Locations of Earthquakes off Fiji

head(quakes)

# Show first 20 rows from the `quakes` dataset
leaflet(data = quakes[1:20,]) %>% addTiles() %>%
  addMarkers(~long, ~lat, popup = ~as.character(mag), label = ~as.character(mag))
```

Note that the marker size is defined based on pixels, and will keep the shape irrespectiev of the zoom level. However, it might become cumbersome to observe this with a large number of dataset. When there are a large number of markers on the map, you can cluster them together using the argument `clusterOptions`.

```{r}
leaflet(quakes) %>% addTiles() %>% addMarkers(
  clusterOptions = markerClusterOptions()
)
```


###Add ons

Various utility functions can be used to augment your map with additional elements. One basic example is given below is to add a distance measuring tool and a minimap.

```{r}
leaflet(quakes) %>% addTiles() %>% addMarkers(
  clusterOptions = markerClusterOptions()
) %>% addMeasure() %>% addMiniMap()
```

These are the basics of using the `leaflet` package and just barely skimmed the surface of what this package is capable of doing. For more details, check the leaflet documention site listed below. The R markdown for this tutorial is also given below. Hope you had fun following through this tutorial.

***
The R markdown for this tutorial: [Leaflet tutorial](leafletR.Rmd)

documentation source: https://rstudio.github.io/leaflet/

Full extent of leaflet application: https://leafletjs.com/examples.html