-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathggmap_leaflet.Rmd
471 lines (377 loc) · 12.7 KB
/
ggmap_leaflet.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
---
title: My Google Timeline data with ` `r params$package` `
author: |
| Matthew Malishev
|
| @darwinanddavis
|
#bibliography:/Users/malishev/Documents/Melbourne Uni/Thesis_2016/library.bib
fontsize: 10
geometry: margin=1in
documentclass: article
linkcolor: blue
urlcolor: blue
citecolor: red
output:
html_document:
highlight: tango
code_folding: show
toc: yes
toc_depth: 4
number_sections: no
toc_float: yes
pdf_document:
includes:
in_header: # add .tex file with header content
highlight: tango
template: null
toc: yes
toc_depth: 4
number_sections: false
fig_width: 4
fig_height: 5
fig_caption: true
df_print: tibble
citation_package: biblatex # natbib
latex_engine: xelatex #pdflatex # lualatex
keep_tex: true # keep .tex file in dir
word_document:
highlight: tango
keep_md: yes
pandoc_args: --smart
#reference: mystyles.docx
toc: yes
inludes:
before_body: before_body.tex
subtitle:
tags:
- nothing
- nothingness
params:
package: "leaflet"
dir: "/Users/malishev/Documents/Data/gggmap"
date: !r Sys.Date()
session: !r sessionInfo()
version: !r getRversion()
email: "matthew.malishev@gmail.com"
doi: https://github.com/darwinanddavis/UsefulCode
classoption: portrait
# ^['https://github.com/darwinanddavis/UsefulCode'] # footnote
vignette: >
%\VignetteIndexEntry{Useful R code}
%\VignetteEncoding{UTF-8}
%\VignetteEngine{knitr::rmarkdown}
---
<script type="text/x-mathjax-config">
MathJax.Hub.Config({ TeX: { equationNumbers: {autoNumber: "all"} } });
</script>
```{r, set-options, echo = FALSE, cache = FALSE}
options(width=100)
knitr::opts_chunk$set(
eval = F, # run all code
echo = T, # show code chunks in output
comment = "",
tidy.opts=list(width.cutoff=100), # set width of code chunks in output
tidy=T, # make output as tidy
message = F, # mask all messages
warning = F, # mask all warnings
size="small" # set code chunk size
)
# https://github.com/ucb-stat133/stat133-fall-2016/blob/master/hws/hw02-tables-ggplot.Rmd
knitr::opts_knit$set(root.dir=paste0(params$dir,"/")) # set working dir
setwd(paste0(params$dir,"/")) # for running just in R not knitr
```
\newpage
Date: `r params$date`
R version: `r params$version`
*Corresponding author: `r params$email`
This document can be found at `r params$doi`
\
R session info
```{r, echo=F,aval=F}
params$session
```
\newpage
## Overview
My Google timeline data with `r params$package`.
**Need to export as HTML, then open in internet browser.**
### Install dependencies
```{r, load packages, include=T, cache=F, message=F, warning=F, results='hide'}
packages <- c("rgdal","dplyr","zoo","RColorBrewer","viridis","plyr","digitize","jpeg","devtools","imager","dplyr","ggplot2","ggridges","ggjoy","ggthemes","svDialogs","data.table","tibble","extrafont","sp","leaflet","htmltools")
if (require(packages)) {
install.packages(packages,dependencies = T)
require(packages)
}
lapply(packages,library,character.only=T)
```
### [Gallery of map styles](https://leaflet-extras.github.io/leaflet-providers/preview/)
\
### Leaflet
```{r,eval=T}
require(leaflet)
# airbnb data
amdam <- read.csv("amdam.csv",header=T,sep=",",stringsAsFactors = T)
ll <- amdam[1,]
ll <- ll[,c("latitude","longitude")]
par(bg="black")
cleanliness <- amdam[,"review_scores_cleanliness"] %>% unique
cleanliness[is.na(cleanliness)] <- 1
beds <- amdam[,"beds"] %>% unique
beds[is.na(beds)] <- 1
beds <- beds + 1
colv <- "orange"
site_names <- paste0("Rating: ", amdam$review_scores_rating,
"\n\nCheck-in: ", amdam$review_scores_checkin,
"\nCleanliness: ", amdam$review_scores_cleanliness,
"\nLocation: ", amdam$review_scores_location
)
amdam[is.na(amdam)] <- 1
require(leaflet)
map <- leaflet() %>%
setView(amdam[1,"longitude"],amdam[1,"latitude"],zoom=12) %>%
addTiles() %>%
addCircleMarkers(amdam[,"longitude"],
amdam[,"latitude"],
radius = amdam$review_scores_cleanliness/20,
stroke = TRUE,
weight = 3,
opacity = 0.5,
color = colv,
fillColor = colv,
label=site_names,
popup=site_names) %>%
addProviderTiles("CartoDB.DarkMatter")
map
```
```{r,echo=F}
require(leaflet)
amdam[is.na(amdam)] <- 1 # turn nas into 1
avail_30 <- amdam %>% dplyr::filter(amdam$availability_30 > 1)
avail_60 <- amdam %>% dplyr::filter(amdam$availability_60 > 1)
avail_90 <- amdam %>% dplyr::filter(amdam$availability_90 > 1)
require(leaflet)
map <- leaflet() %>%
setView(amdam[1,"longitude"],amdam[1,"latitude"],zoom=12) %>%
addTiles() %>%
addCircleMarkers(avail_30[,"longitude"],
avail_30[,"latitude"],
radius = avail_30$review_scores_cleanliness/20,
stroke = TRUE,
weight = 3,
opacity = 0.5,
color = "lightblue",
fillColor = "lightblue",
label=site_names,
popup=site_names) %>%
addCircleMarkers(avail_60[,"longitude"],
avail_60[,"latitude"],
radius = avail_60$review_scores_cleanliness/20,
stroke = TRUE,
weight = 3,
opacity = 0.5,
color = "pink",
fillColor = "pink",
label=site_names,
popup=site_names) %>%
addProviderTiles("CartoDB.DarkMatter")
map
```
### Interactive label options and custom tiles
```{r, eval=T}
require(leaflet)
require(dplyr)
require(geosphere)
require(htmltools)
setview <- c(7.369722,12.354722)
marker <- c(-26.828764,-17.009277)
mp <- data.frame(
"name" = c("Melbourne","Atlanta"),
"lat" = c(-37.813629,33.748997),
"lon" = c(144.963058,-84.387985)
)
latlon_matrix <- matrix(c(mp[,"lon"],mp[,"lat"]),ncol=2)
custom_tile <- "http://a.sm.mapstack.stamen.com/(positron,(mapbox-water,$776699[hsl-color]),(buildings,$002bff[hsl-color]),(parks,$6abb9d[hsl-color]))/{z}/{x}/{y}.png"
colv <- "#4C3661"
opac <- 0.5
site_names <- mp$name
ttl <- "Debunking Flat Earth theory 101"
weblink <- "https://www.tfes.org/contact.php" # weblink
webname <- "Flat Earth Society"
href <- paste0("<b><a href=",weblink,">",webname,"</a></b>")
text_label <- "This is curved"
popup_label <- paste(sep = "<br/>",
"This part wraps around", paste0("@",href)
)
# label options
marker_label_opt <- labelOptions(textsize = "20px",opacity = 0.5,offset = c(0,0))
popup_label_opt <- popupOptions(closeOnClick = F, closeButton = FALSE, textOnly = F, textsize = "2px")
text_label_opt <- labelOptions(noHide = F, direction = 'top', textOnly = F, opacity = 1,offset = c(0,0))
# title
tag.map.title <- tags$style(
HTML(".leaflet-control.map-title {
transform: translate(-50%,20%);
position: fixed !important;
left: 50%;
text-align: center;
padding-left: 10px;
padding-right: 10px;
background: white; opacity: 0.7;
font-weight: bold;
font-size: 25px;
}"
))
title <- tags$div(
tag.map.title, HTML(ttl)
)
# map
map <- gcIntermediate(latlon_matrix[1,],
latlon_matrix[2,],
n=100,
addStartEnd=T,
sp=T) %>%
leaflet() %>%
setView(setview[2],setview[1],zoom=3) %>%
addTiles(custom_tile) %>%
addCircleMarkers(mp[,"lon"],
mp[,"lat"],
radius = 10,
stroke = TRUE,
weight = 3,
opacity = opac,
color = colv,
fillColor = colv,
label=paste(site_names),
labelOptions = marker_label_opt
) %>%
addPolylines(
color = colv,
opacity = opac,label = text_label, labelOptions = text_label_opt) %>%
addPopups(marker[2],marker[1], popup = popup_label,
options = popup_label_opt
) %>%
addControl("@darwinanddavis", position = "topright") %>%
addControl(title, position = "topleft", className="map-title")
map
# save_html(map,"flatearth_2.html")
```
# Custom map tiles
```{r}
require(leaflet)
# flat earth
custom_tile <- "http://d.sm.mapstack.stamen.com/(positron,(parks,$3bcdd5[hsl-color]),(streets-and-labels,$e2d2f0[hsl-color]),(buildings,$e2d2f0[hsl-color]))/{z}/{x}/{y}.png"
custom_tile <- "http://d.sm.mapstack.stamen.com/((darkmatter,$00ffff[hsl-color]),(mapbox-water,$00589c[hsl-color]),(parks,$ff9a30[source-in]))/{z}/{x}/{y}.png"
# conference sites
custom_tile <- "http://c.sm.mapstack.stamen.com/(toner-lite,(mapbox-water,$000[@80]),(parks,$000[@70]),(buildings,$fabe68[hsl-color]))/{z}/{x}/{y}.png"
custom_tile <- "http://b.sm.mapstack.stamen.com/((mapbox-water,$f2f7ff[hsl-color]),(positron,$f2f7ff[hsl-color]),(buildings,$e2edff[hsl-color]),(parks,$d5e5ff[hsl-color]))/{z}/{x}/{y}.png"
custom_tile <- "http://b.sm.mapstack.stamen.com/((mapbox-water,$f2f7ff[hsl-color]),(positron,$f2f7ff[hsl-color]),(buildings,$e2edff[hsl-color]),(parks,$2c403b[hsl-color]))/{z}/{x}/{y}.png"
leaflet() %>%
setView(144.963058,-37.813629,zoom=12) %>%
addTiles(custom_tile)
```
### Flight connections maps
```{r}
# flight connection maps
# https://www.gis-blog.com/flight-connection-map-with-r/
# http://kateto.net/network-visualization
# https://stackoverflow.com/questions/54362265/plotting-routes-that-cross-the-international-dateline-using-leaflet-library-in-r
```
### Drawing networks of lines e.g. roads
```{r}
# https://rpubs.com/walkerke/points_to_line
```
### Adding images within popup markers
<!-- https://stackoverflow.com/questions/32352539/plotting-barchart-in-popup-using-leaflet-library/36237460#36237460 -->
<!-- https://stackoverflow.com/questions/36433899/image-in-r-leaflet-marker-popups -->
### Line breaks in labels and popups
```{r}
require(dplyr)
require(htmltools)
require(purrr)
long <- c(147.5, 147.5, 147.5, 147, 147)
lat <- c(-36.5, -36.5, -36.5, -36, -36)
label <- c(1, 1, 2, 1, 2)
markers <- data.frame(lat,long,label)
# label linebreak
label_breaks <- paste(
"<strong> Lat: </strong>", markers$lat, "<br/>",
"<strong> Lon: </strong>", markers$long, "<br/>"
) %>% map(htmltools::HTML)
# popup linebreak method 1
popup_breaks1 <- paste(sep = "<br/>",
"<strong> Line1: </strong>", markers$label,
"",
"<strong> Line2: </strong>", markers$label,
""
)
# popup break 2 # Aggregate method
popup_breaks2 <- aggregate(label ~ lat + long, markers, paste, collapse = "<br/>")
# Markers with all of the labels
leaflet() %>%
addTiles() %>%
addMarkers(lng=markers$long, lat= markers$lat,
label=label_breaks,
popup= popup_breaks2
)
```
### Update map elements with leaflet proxy
E.g. widget updates that don't refresh map each iteration
<!-- https://www.youtube.com/watch?v=G5BDub -->
### Update map elements with hover
<!-- https://www.kaggle.com/skirmer/exploratory-analysis-of-austin-crime-with-maps -->
```{r}
require(maps)
require(leaflet)
# world.cities data from \maps
world_cities <- with(world.cities, data.frame(
"city" = name,
"country" = country.etc,
"lat" = lat,
"lon" = long,
"population" = pop
)
)
world_cities %>% str
latlon <- world_cities[,c("lat","lon")]
radius <- world_cities[,"population"]/1000000
popup <- world_cities[,"city"]
label <- world_cities[,"country"]
# style
custom_tile <- "http://c.sm.mapstack.stamen.com/(toner-lite,(mapbox-water,$000[@80]),(parks,$000[@70]),(buildings,$fabe68[hsl-color]))/{z}/{x}/{y}.png"
colv <- "#F90F40"
opac <- 0.3
map <- leaflet() %>%
setView(0,0,zoom=3) %>%
addTiles(custom_tile) %>%
addCircleMarkers(latlon[,"lon"],
latlon[,"lat"],
radius = radius,
stroke = TRUE,
weight = 3,
opacity = opac,
color = colv,
fillColor = colv,
label = label,
popup = popup
)
map
```
### Add minimap
<!-- https://rstudio.github.io/leaflet/morefeatures.html -->
### Add measurement tool
```{r}
# https://rstudio.github.io/leaflet/morefeatures.html
leaflet %>%
setview(0,0,13) %>%
addTiles(custom_tile) %>%
fitBounds(13.76134, 52.675499, 13.0884, 52.33812) %>%
addMeasure(
position = "bottomleft",
primaryLengthUnit = "meters",
primaryAreaUnit = "sqmeters",
activeColor = "#3D535D",
completedColor = "#7D4479")
```
### Improve render performance with `leafgl`
[https://github.com/r-spatial/leafgl](https://github.com/r-spatial/leafgl)
```{r}
```