There and Back Again competition entry https://shiny.petras.space/commute/
rstats
rshiny
census
competition
leaflet
javascript
stats-nz

app.R 12KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300
  1. library(shiny)
  2. library(shinyjs)
  3. library(leaflet)
  4. library(rgdal)
  5. library(dplyr)
  6. library(leaflet.extras)
  7. library(shinyWidgets)
  8. source("leafletfunctions.R")
  9. source("extras.R")
  10. # work_travel <- read_csv("../travel-work.csv")
  11. load(file="datasets.RData")
  12. shpf <- readOGR(dsn="sa20025WGSfilcth")
  13. sa.in.dest <- shpf@data$SA22018_V1 %in% work_to$work_code
  14. sa.in.home <- shpf@data$SA22018_V1 %in% work_from$res_code
  15. transport.t <- c("Work at home", "Private car", "Company car",
  16. "Carpool", "Bus", "Train", "Bicycle", "Walk",
  17. "Ferry", "Other", "None")
  18. cols.labs <- c(transport.t[1:10], "Total")
  19. codelist <- shpf@data %>%
  20. mutate(sa2_code = as.numeric(as.character(SA22018_V1))) %>%
  21. select(sa2_code)
  22. startcols.res <- codelist %>% left_join(work_from, by = c("sa2_code" = "res_code"))
  23. startcols.res <- tencols[startcols.res$MAX]
  24. startcols.res <- ifelse(is.na(startcols.res), "#808080", startcols.res)
  25. startcols.work <- codelist %>% left_join(work_to, by = c("sa2_code" = "work_code"))
  26. startcols.work <- tencols[startcols.work$MAX]
  27. startcols.work <- ifelse(is.na(startcols.work), "#808080", startcols.work)
  28. hrstr <- "<hr style='border-top: 1px solid #000;'/>"
  29. # Define UI
  30. ui <- fluidPage(
  31. useShinyjs(),
  32. leafletjs,
  33. tags$style(type = "text/css", extracss),
  34. leafletOutput("map"),
  35. absolutePanel(top = 10, right = 10, id="mapcontrol",
  36. radioButtons("radioinout", label="Show commuters who",
  37. choiceNames = list(
  38. HTML("<p>Commute <b>from</b> selected area</p>"),
  39. HTML("<p>Commute <b>to</b> selected area</p>")),
  40. choiceValues = list(
  41. "res",
  42. "work"
  43. ),
  44. inline = FALSE),
  45. radioButtons("radiocolour",
  46. label = "Colour by",
  47. choiceNames = list(
  48. HTML("<p>Most common commute method</p>"),
  49. HTML("<p>Number of commuters</p>")
  50. ),
  51. choiceValues = list(
  52. "type",
  53. "number"
  54. ),
  55. inline = FALSE),
  56. div(id="locinfo",
  57. htmlOutput("lochtml"))),
  58. absolutePanel(top = 25, right = 10, id="control2",
  59. materialSwitch("controlswitch", value=TRUE, right=TRUE,
  60. inline=TRUE, status="info")),
  61. absolutePanel(bottom = 30, left = 10, id="loading",
  62. p("Loading...")),
  63. absolutePanel(bottom=26, right=10, left=10, top=10, id="infopanel",
  64. p("Test")),
  65. absolutePanel(bottom=10, right=10, id="infobuttoncontainer",
  66. prettyToggle("mapinfobutton", label_on = "Info",
  67. label_off = "Info", icon_on=icon("times"),
  68. icon_off = icon("info"),
  69. animation = "pulse",
  70. inline = TRUE,
  71. status_on = "danger",
  72. status_off = "info")
  73. )
  74. )
  75. # Define server logic
  76. server <- function(input, output) {
  77. sel.SA2.code <- reactiveVal(0)
  78. attribupdate <- FALSE
  79. output$map <- renderLeaflet({
  80. leaf <- leaflet(shpf, options = leafletOptions(minZoom = 3, maxZoom = 13)) %>%
  81. addPolygons(color="#000", opacity = 1, weight=1,
  82. fillColor = startcols.res,
  83. layerId = ~SA22018_V1,
  84. label = shpf@data$SA22018__1,
  85. fillOpacity = 1) %>%
  86. setView(174, -41, 6) %>%
  87. addResetMapButton() %>%
  88. addLegend(position = "topleft",
  89. colors = c(tencols, "#808080"),
  90. labels = transport.t, opacity = 1,
  91. title = "Commute method")
  92. shinyjs::hideElement(selector="#loading p", asis = TRUE,
  93. anim=TRUE, animType = "slide", time=10)
  94. leaf
  95. })
  96. updateMap <- function() {
  97. shinyjs::showElement(selector="#loading p", asis = TRUE,
  98. anim=TRUE, animType = "slide")
  99. selcode <- sel.SA2.code()
  100. selcode <- ifelse(is.na(selcode), 0, selcode)
  101. psel <- selcode %in% shpf@data$SA22018_V1
  102. if (input$radiocolour == "type") {
  103. if (input$radioinout == "work") {
  104. fcols <- startcols.work
  105. if (psel) {
  106. codvs <- work_simp %>% filter(work_code == selcode)
  107. codvs <- codelist %>% left_join(codvs, by=c("sa2_code" = "res_code"))
  108. codvs <- tencols[codvs$MAX]
  109. fcols <- ifelse(is.na(codvs), "#808080", codvs)
  110. }
  111. } else {
  112. fcols <- startcols.res
  113. if (psel) {
  114. codvs <- work_simp %>% filter(res_code == selcode)
  115. codvs <- codelist %>% left_join(codvs, by=c("sa2_code" = "work_code"))
  116. codvs <- tencols[codvs$MAX]
  117. fcols <- ifelse(is.na(codvs), "#808080", codvs)
  118. }
  119. }
  120. lp <- leafletProxy("map", data = shpf) %>%
  121. setShapeStyle(layerId = ~SA22018_V1, fillColor = fcols) %>%
  122. clearControls() %>%
  123. addLegend(position = "topleft",
  124. colors = c(tencols, "#808080"),
  125. labels = transport.t, opacity = 1,
  126. title = "Commute method"
  127. ) %>%
  128. clearGroup("hpoly")
  129. } else {
  130. if (input$radioinout == "work") {
  131. if (psel) {
  132. codvs <- work_simp %>% filter(work_code == selcode)
  133. codvs <- codelist %>% left_join(codvs, by=c("sa2_code" = "res_code"))
  134. cvals <- ifelse(codvs$total == 0, NA, codvs$total)
  135. } else {
  136. codvs <- codelist %>%
  137. left_join(work_to, by = c("sa2_code" = "work_code"))
  138. cvals <- ifelse(codvs$total == 0, NA, codvs$total)
  139. }
  140. } else {
  141. if (psel) {
  142. codvs <- work_simp %>% filter(res_code == selcode)
  143. codvs <- codelist %>% left_join(codvs, by=c("sa2_code" = "work_code"))
  144. cvals <- ifelse(codvs$total == 0, NA, codvs$total)
  145. } else {
  146. codvs <- codelist %>%
  147. left_join(work_from, by = c("sa2_code" = "res_code"))
  148. cvals <- ifelse(codvs$total == 0, NA, codvs$total)
  149. }
  150. }
  151. cvr <- range(cvals, na.rm = TRUE)
  152. binner <- colorBin(c("white", "red"), cvr, bins = 7, pretty = TRUE)
  153. lp <- leafletProxy("map", data = shpf) %>%
  154. setShapeStyle(layerId = ~SA22018_V1, fillColor = binner(cvals)) %>%
  155. clearControls() %>%
  156. addLegend(position = "topleft",
  157. pal = binner,
  158. values = cvals, opacity = 1,
  159. na.label = "None",
  160. title = "Number of commuters") %>%
  161. clearGroup("hpoly")
  162. }
  163. if (psel) {
  164. lp %>% addPolygons(group = "hpoly",
  165. weight = 4,
  166. data = shpf[which(shpf@data$SA22018_V1 == selcode),],
  167. color = "#000000",
  168. fill = FALSE, opacity = 1)
  169. }
  170. shinyjs::hideElement(selector="#loading p", asis=TRUE,
  171. anim=TRUE, animType = "slide",
  172. time = 1)
  173. }
  174. observeEvent(input$map_click, ignoreInit = TRUE, {
  175. p <- input$map_click
  176. pdat <- data.frame(Longitude = p$lng,
  177. Latitude =p$lat)
  178. coordinates(pdat) <- ~ Longitude + Latitude
  179. proj4string(pdat) <- proj4string(shpf)
  180. ppoly <- over(pdat, shpf)
  181. codetmp <- as.numeric(as.character(ppoly[1,"SA22018_V1"]))
  182. codetmp <- ifelse(is.na(codetmp), 0, codetmp)
  183. sel.SA2.code(ifelse(sel.SA2.code() == codetmp, 0, codetmp))
  184. updateMap()
  185. })
  186. observeEvent(input$map_zoom, once=TRUE, {
  187. if (!attribupdate) {
  188. print(attribupdate)
  189. shinyjs::html(selector=".leaflet-control-attribution.leaflet-control",
  190. html = attribhtml)
  191. attribupdate <<- TRUE
  192. }
  193. })
  194. observeEvent(input$map_shape_mouseover, once=TRUE,{
  195. # Backup
  196. if (!attribupdate) {
  197. print(attribupdate)
  198. shinyjs::html(selector=".leaflet-control-attribution.leaflet-control",
  199. html = attribhtml)
  200. attribupdate <<- TRUE
  201. }
  202. })
  203. observeEvent(input$radioinout, ignoreInit = TRUE, {
  204. updateMap()
  205. })
  206. observeEvent(input$infobutton, {
  207. print(input$infobutton)
  208. })
  209. observeEvent(input$radiocolour, ignoreInit = TRUE, {
  210. updateMap()
  211. })
  212. observeEvent(input$controlswitch, ignoreInit = TRUE, {
  213. shinyjs::toggleElement("mapcontrol", anim=TRUE,
  214. time = 0.5)
  215. })
  216. observeEvent(input$mapinfobutton, ignoreInit = TRUE, {
  217. shinyjs::toggleElement("infopanel", anim=TRUE,
  218. time = 1)
  219. })
  220. output$lochtml <- renderUI({
  221. seled <- sel.SA2.code()
  222. seled <- ifelse(is.na(seled), 0, seled)
  223. if (!(seled %in% shpf@data$SA22018_V1)) {
  224. HTML(paste0(hrstr,
  225. "<p><em>No area selected</em></p>"))
  226. } else {
  227. namesel <- shpf@data$SA22018__1[shpf@data$SA22018_V1 == seled]
  228. if (input$radiocolour == "type") {
  229. str <- sprintf("<b>%s</b>", namesel)
  230. if (input$radioinout == "work") {
  231. str <- sprintf("<p>Commuting method of people who <b>work</b> in</p>
  232. <p><b><u>%s</u></b></p>", str)
  233. vals <- as.numeric(work_to[work_to$work_code == seled, 5:15])
  234. vals <- ifelse(is.na(vals), 0, vals)
  235. vals <- ifelse(vals < 0, "~0", as.character(vals))
  236. listi <- paste0(sprintf("<li>%s: %s</li>", cols.labs,
  237. vals),
  238. collapse="")
  239. str <- paste0(hrstr, str, "<ul>", listi, "</ul>")
  240. } else {
  241. str <- sprintf("<p>Commuting method of people who <b>live</b> in</p>
  242. <p><u>%s</u></p>", str)
  243. vals <- as.numeric(work_from[work_from$res_code == seled, 5:15])
  244. vals <- ifelse(is.na(vals), 0, vals)
  245. vals <- ifelse(vals < 0, "~0", as.character(vals))
  246. listi <- paste0(sprintf("<li>%s: %s</li>", cols.labs,
  247. vals),
  248. collapse="")
  249. str <- paste0(hrstr, str, "<ul>", listi, "</ul>")
  250. }
  251. HTML(str)
  252. } else {
  253. str <- hrstr
  254. if (input$radioinout == "work") {
  255. val <- as.numeric(work_to[work_to$work_code == seled, 15])
  256. val <- ifelse(is.na(val), 0, ifelse(val < 0, 0, val))
  257. str <- sprintf("%s<p>%d people commute <b>to</b></p>
  258. <p><b><u>%s</u></b></p>", str, val, namesel)
  259. if (val > 0) {
  260. subs <- work_simp %>% filter(work_code == seled) %>%
  261. arrange(desc(total)) %>% head(10)
  262. listi <- paste0(sprintf("<li>%s: %s</li>", subs$res_name,
  263. subs$total),
  264. collapse="")
  265. str <- sprintf("%s<p>Top areas to commute from<p>
  266. <ul>%s</ul>", str, listi)
  267. }
  268. } else {
  269. val <- as.numeric(work_from[work_from$res_code == seled, 15])
  270. val <- ifelse(is.na(val), 0, ifelse(val < 0, 0, val))
  271. str <- sprintf("%s<p>%d people commute <b>from</b></p>
  272. <p><b><u>%s</u></b></p>", str, val, namesel)
  273. if (val > 0) {
  274. subs <- work_simp %>% filter(res_code == seled) %>%
  275. arrange(desc(total)) %>% head(10)
  276. listi <- paste0(sprintf("<li>%s: %s</li>", subs$work_name,
  277. subs$total),
  278. collapse="")
  279. str <- sprintf("%s<p>Top areas to commute to<p>
  280. <ul>%s</ul>", str, listi)
  281. }
  282. }
  283. HTML(str)
  284. }
  285. }
  286. })
  287. }
  288. # Run the application
  289. shinyApp(ui = ui, server = server)