-
Notifications
You must be signed in to change notification settings - Fork 15
/
Copy pathindex.Rmd
493 lines (338 loc) · 12.9 KB
/
index.Rmd
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
---
title: "Geography 176A"
subtitle: "Leaflet R"
author: "Mike Johnson & Marcela Suarez"
output:
html_document:
toc: true
toc_float: true
toc_collapsed: true
---
```{r,echo=FALSE}
knitr::opts_chunk$set(message = FALSE, warning = FALSE, comment = "#>", out.width = "100%")
```
This is the supplementary notes and examples for an introduction to leaflet.
It is based on data and examples seen in class
Built on the excellent tutorial from [RStudio](https://rstudio.github.io/leaflet/)
****
If not already installed, install `leaflet`:
```{r, eval = FALSE}
install.packages("leaflet")
```
Then attach the library:
```{r}
library(leaflet)
```
Bring in the other needed libraries:
```{r}
library(sf)
library(tidyverse)
library(USAboundaries)
```
---
# Basic Usage
Creating a Leaflet map requires a few basic steps (not dissimilar to ggplot):
1. Initialize a map widget by calling leaflet().
2. Add layers (i.e., features) to the map by using layer functions (e.g. addTiles, addMarkers, addPolygons,...)
3. Print the map widget to display it.
---
Here’s a basic example:
```{r, fig.height= 4}
leaflet() %>%
addTiles() %>%
addMarkers(lng=-119.8489, lat=34.4140, popup="UCSB")
```
---
- By default, leaflet sets the view of the map to the range of latitude/longitude data in the map layers
- You can adjust these if needed using:
- `setView() `: sets the center of the map view and the zoom level;
- `fitBounds()`: fits the view into the rectangle [lng1, lat1] – [lng2, lat2];
- `clearBounds()` clears the bound
****
# Basemaps
### Default (OpenStreetMap) Tiles
The easiest way to add tiles is by calling `addTiles()` with no arguments; by default, OpenStreetMap tiles are used.
```{r}
(leaflet() %>%
setView(lng=-119.8489, lat=34.4140, zoom = 12) %>%
addTiles())
```
### Third-Party Tiles
- Many third-party basemaps can be added using the `addProviderTiles()` function
- As a convenience, leaflet provides a named list of all the third-party tile providers supported by the plugin: just type `providers$` and choose from one of the options.
```{r}
length(providers)
names(providers) %>%
head()
```
> Note that some tile set providers require you to register. You can pass access tokens/keys, and other options, to the tile provider by populating the options argument with the providerTileOptions() function.
- I would personal stick with the OSM, CartoDB, ESRI, and Stamen servers ... [see more here] (https://leaflet-extras.github.io/leaflet-providers/preview/)
Below are a few examples:
### CartoDB
```{r}
leaflet() %>%
setView(lng=-119.8489, lat=34.4140, zoom = 12) %>%
addProviderTiles(providers$CartoDB)
```
### Stamen.Toner
```{r}
leaflet() %>%
setView(lng=-119.8489, lat=34.4140, zoom = 12) %>%
addProviderTiles(providers$Stamen.Toner)
```
### ESRI Imagery
```{r}
leaflet() %>%
setView(lng=-119.8489, lat=34.4140, zoom = 12) %>%
addProviderTiles(providers$Esri.WorldImagery)
```
### Stamen.TopOSMRelief
```{r}
leaflet() %>%
setView(lng=-119.8489, lat=34.4140, zoom = 12) %>%
addProviderTiles(providers$Stamen.TopOSMRelief)
```
### Combining Tile Layers
You can stack multiple tile layers if the front tiles have some level of opacity. Here we layer the Stamen.TonerLines with aerial imagery
```{r}
leaflet() %>%
setView(lng=-119.8489, lat=34.4140, zoom = 12) %>%
addProviderTiles(providers$Esri.WorldImagery) %>%
addProviderTiles(providers$Stamen.TonerLines, options = providerTileOptions(opacity = .5))
```
---
# Markers
Markers are one way to identify point information on a map:
***
#### Example Starbucks data:
```{r}
(starbucks = read_csv('data/directory.csv') %>%
filter(City %in% c("Goleta", "Santa Barbara")) %>%
st_as_sf(coords = c("Longitude", "Latitude"), crs = 4326) %>%
select(store_name = `Store Name`, phone = `Phone Number`, address = `Street Address`, city = City, brand = Brand))
```
### Markers
Markers are added using the `addMarkers` or `addAwesomeMarkers`
Their default appearance is a blue dropped pin.
As with most layer functions,
- the `popup` argument adds a message to be displayed on click
- the `label` argument display a text label either on hover
```{r}
leaflet() %>%
addProviderTiles(providers$CartoDB) %>%
addMarkers(data = starbucks, popup = ~store_name, label = ~city)
```
### [Awesome Icons](https://github.com/lvoogdt/Leaflet.awesome-markers)
Using the Font Awesome Icons seen in lab one, we can make markers with more specific coloring and icons
- Here we define the icon as a green marker with a coffee icon from the fa library
- For fun we can make the coffee cups spin...
We then use addAwesomeMarkers to spcifiy the icon we created using the icon argument:
```{r}
icons = awesomeIcons(icon = 'coffee', markerColor = "green", library = 'fa', spin = TRUE)
leaflet(data = starbucks) %>% addProviderTiles(providers$CartoDB) %>%
addAwesomeMarkers(icon = icons, popup = ~store_name)
```
### Custom Popups
You can use HTML, CSS, and Java Script to modify your pop-ups
For example, we can associate the name of the Starbucks locations with their google maps URL as an hyper reference (href):
```{r}
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)
```
We can then add our custom popup to our icons:
```{r}
leaflet(data = starbucks) %>%
addProviderTiles(providers$CartoDB) %>%
addAwesomeMarkers(icon = icons,
label = ~address, popup = pop)
```
### Circle Markers
Circle markers are much like regular circles (shapes), except their radius in onscreen pixels stays constant _regardless_ of zoom level (z).
```{r}
leaflet(data = starbucks) %>%
addProviderTiles(providers$CartoDB) %>%
addCircleMarkers(label = ~address, popup = pop)
```
#### Marker Clustering
Sometimes while mapping many points, it is useful to cluster them. For example lets plot all starbucks in the world!
```{r}
all_sb = read_csv('data/directory.csv') %>%
filter(!is.na(Latitude)) %>%
st_as_sf(coords = c("Longitude", "Latitude"), crs = 4326)
leaflet(data = all_sb) %>%
addProviderTiles(providers$CartoDB) %>%
addMarkers(clusterOptions = markerClusterOptions())
```
****
# Adding color ramps
- Colors can be add by factor, numeric, bins, or quartiles using the built in leaflet functions
- Each of these are defined by a palette, and a domain
The palette argument can be any of the following:
- A character vector of RGB or named colors.
- Examples: palette(), c("#000000", "#0000FF", "#FFFFFF"), topo.colors(10)
- The name of an RColorBrewer palette
- Examples: "BuPu" or "Greens".
- The full name of a viridis palette:
- Examples: "viridis", "magma", "inferno", or "plasma".
- A function that receives a single value between 0 and 1 and returns a color.
- Examples: colorRamp(c("#000000", "#FFFFFF"), interpolate = "spline").
The domain is the values - named by variable - that the color palette should range over
```{r}
# ?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)
```
****
# Shapes (Polylines, Polygons, Circles)
#### Getting some data ...
```{r}
(covid = readr::read_csv('https://raw.githubusercontent.com/nytimes/covid-19-data/master/live/us-states.csv') %>%
filter(date == max(date)) %>%
right_join(USAboundaries::us_states(), by = c("state" = "name")) %>%
filter(!stusps %in% c("AK","PR", "HI")) %>%
st_as_sf())
```
### Polygons
Adding those cases counts to polygons over a `YlOrRd` color ramp
```{r}
leaflet() %>%
addProviderTiles(providers$CartoDB) %>%
addPolygons(data = covid,
fillColor = ~colorQuantile("YlOrRd", confirmed_cases)(confirmed_cases),
color = NA,
label = ~state_name)
```
### Circles
```{r}
leaflet() %>%
addProviderTiles(providers$CartoDB.DarkMatter) %>%
addCircles(data = st_centroid(covid),
fillColor = ~colorQuantile("YlOrRd", cases)(cases),
color = NA,
fillOpacity = .5,
radius = ~cases/3,
label = ~cases)
```
# Web based data
### USGS Gage near UCSB: ID-11120000
https://waterdata.usgs.gov/monitoring-location/11120000/
```{r, fig.align='center', fig.width = 5, echo = FALSE}
knitr::include_graphics('img/16-usgs-gage.png')
```
### [Network Linked Data](https://labs.waterdata.usgs.gov/about-nldi/index.html) (GeoJSON)
https://labs.waterdata.usgs.gov/api/nldi/linked-data/nwissite/USGS-11120000/navigate/UT
Trance the Upper Tributary (UT) of the USGS-11120000
```{r, fig.align='center', fig.width = 10, echo = FALSE}
knitr::include_graphics('img/16-geojson.png')
```
### Adding "Web data" to the map
```{r}
# site ID
id = "11120000"
# base URL
base ="https://labs.waterdata.usgs.gov/api/nldi/linked-data/"
# Reading sf for URLs in line
leaflet() %>%
addProviderTiles(providers$CartoDB) %>%
addPolylines(data = read_sf(paste0(base,'nwissite/USGS-',id,'/navigate/UT'))) %>%
addPolygons(data = read_sf(paste0(base,'nwissite/USGS-',id,'/basin')),
fillColor = "transparent", color = "black")
```
---
### [WMS Tiles](https://leafletjs.com/examples/wms/wms.html)
WMS tiles can be added directly to a map. Here we use the NEXRAD rainfall information (refelctivity) from the Iowa Mesonet Program
(You may need to scroll out to find an)
```{r}
conus = filter(us_states(), !stusps %in% c("AK", "PR", "HI"))
leaflet() %>%
addProviderTiles(providers$CartoDB) %>%
addPolygons(data = st_union(conus), fillColor = "transparent",
color = "black", weight = 1) %>%
addWMSTiles(
"http://mesonet.agron.iastate.edu/cgi-bin/wms/nexrad/n0r.cgi",
layers = "nexrad-n0r-900913",
options = WMSTileOptions(format = "image/png", transparent = TRUE)
)
```
# Layer Controls
Uses Leaflet's built-in layers control you can choose one of several base layers, and any number of overlay layers to view.
By defining groups, you have the ability to toogle layers, and overlays on/off.
```{r, out.height="50%", eval = F}
leaflet() %>%
addProviderTiles(providers$CartoDB, group = "Grayscale") %>%
addProviderTiles(providers$Esri.WorldTerrain, group = "Terrain") %>%
addPolylines(data = read_sf(paste0(base,'nwissite/USGS-',id,'/navigate/UT'))) %>%
addPolygons(data = read_sf(paste0(base,'nwissite/USGS-',id,'/basin')), fillColor = "transparent", color = "black", group = "basin") %>%
addWMSTiles("http://mesonet.agron.iastate.edu/cgi-bin/wms/nexrad/n0r.cgi", layers = "nexrad-n0r-900913",
options = WMSTileOptions(format = "image/png", transparent = TRUE)) %>%
addLayersControl(overlayGroups = c("basin"), baseGroups = c("Terrain", "Grayscale"))
```
# 'Function-ize'
You can wrap your mapping code in functions to allow reusability
```{r}
watershed_map = function(gage_id){
leaflet() %>%
addProviderTiles(providers$CartoDB) %>%
addPolylines(data = read_sf(paste0(base,'nwissite/USGS-',gage_id,'/navigate/UT'))) %>%
addPolygons(data = read_sf(paste0(base,'nwissite/USGS-',gage_id,'/basin')),
fillColor = "transparent", color = "black", group = "basin") %>%
addWMSTiles("http://mesonet.agron.iastate.edu/cgi-bin/wms/nexrad/n0r.cgi", layers = "nexrad-n0r-900913",
options = WMSTileOptions(format = "image/png", transparent = TRUE))
}
```
```{r}
watershed_map("07382000")
```
### Adding Details
- Measures, graticules, and inset maps
```{r}
watershed_map("07382000") %>%
addMeasure() %>%
addGraticule() %>%
addMiniMap()
```
### [leafem](https://github.com/r-spatial/leafem) (new library)
- Home buttons and Mouse Coordinates
- Support for raster and stars objects (to come)
```{r}
watershed_map("07382000") %>%
addMeasure() %>%
addGraticule() %>%
leafem::addHomeButton(group = "basin") %>%
leafem::addMouseCoordinates()
```
### [leafpop](https://github.com/r-spatial/leafpop) (new library)
- Popup Tables
```{r}
leaflet(data = starbucks) %>%
addProviderTiles(providers$CartoDB) %>%
addCircleMarkers(
color = ~pal(city),
fillOpacity = .5,
stroke = FALSE,
popup = leafpop::popupTable(starbucks)
)
```
Making that table nicer...
```{r}
leaflet(data = starbucks) %>% addProviderTiles(providers$CartoDB) %>%
addCircleMarkers(
color = ~pal(city), fillOpacity = .5,
stroke = FALSE,
popup = leafpop::popupTable(st_drop_geometry(starbucks[,1:5]), feature.id = FALSE, row.numbers = FALSE)
)
```
# [Mapview](https://r-spatial.github.io/mapview/)
- easy, but less control
- Support for raster and stars objects (to come in our class)
- Implements many of the `leafem` and `leafpop` functionalities
```{r}
library(mapview)
mapview(starbucks)
```