lvalnegri

r_mapping_leaflet-notes.R

May 16th, 2018
342
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
R 7.51 KB | None | 0 0
  1. # http://www.nytimes.com/projects/elections/2013/nyc-primary/mayor/map.html
  2. # http://www.washingtonpost.com/sf/local/2013/11/09/washington-a-world-apart/?utm_term=.cc3aa0c4e149
  3. # https://leanpub.com/leaflet-tips-and-tricks/read
  4.  
  5. library(rgdal)
  6. library(leaflet)
  7. library(mapview)
  8. library(htmltools)
  9.  
  10.  
  11. # colorBin, colorFactor, colorNumeric, colorQuantile
  12. map.palette <- 'YlOrRd'
  13. # tiles could be recalled either by including the URL of a particular service or by specifying the provider from the included list
  14. tile <- 'http://tile.mtbmap.cz/mtbmap_tiles/{z}/{x}/{y}.png'
  15.  
  16. mp <- leaflet() %>%
  17.         setView(lng = -2.421976, lat = 53.825564, zoom = 5) %>%
  18.         fitBounds(lng1 = 1.8, lat1 = 49.9, lng2 = -8.3, lat2 = 59.0 ) %>%
  19. #        addProviderTiles(providers$Stamen.TonerLite)
  20.         addTiles(tile)
  21. mp
  22.  
  23. # Tiles layers can also be combined, to multiple informations, using appropriately the opacity option
  24. # mp %>%
  25. #     addProviderTiles(providers$MtbMap, options = providerTileOptions(opacity = 0.7) ) %>%
  26. #     addProviderTiles(providers$Stamen.TonerLines, options = providerTileOptions(opacity = 0.35)) %>%
  27. #     addProviderTiles(providers$Stamen.TonerLabels)
  28.  
  29. db_conn <- dbConnect(MySQL(), group = 'shiny', dbname = 'geography')
  30. centres <- suppressWarnings(data.table(dbReadTable(db_conn, 'centres'), key = 'HSP_id') )
  31. dbDisconnect(db_conn)
  32.  
  33. # In general,
  34. # - the label argument can be used to display a textual or HTML content either on hover or statically (option noHide is respectively FALSE (def) / TRUE)
  35. # - the popup argument can be used to add a small box containing arbitrary HTML to be displayed on click
  36. # Both above have a labelOptions = labelOptions(list of <name = value> options) to deeply customize
  37.  
  38. mp %>%
  39.     addCircles(data = centres,
  40.         lng = ~X_lon, lat = ~Y_lat,
  41.         weight = 10,
  42.         radius = 20,
  43.         color = ~type + 1,
  44.         label = ~as.character(HSP_id),
  45.         labelOptions = labelOptions(
  46.                             opacity = 0.8
  47.         ),
  48.         popup = ~as.character(paste(HSP_id, '-', HSP)),
  49.         popupOptions = labelOptions(
  50.                             opacity = 0.8
  51.         )
  52.     )
  53.  
  54. mp %>% addMarkers(data = centres,
  55.         lng = ~X_lon, lat = ~Y_lat,
  56. #        color = ~type,
  57.         label = ~as.character(HSP_id),
  58.         labelOptions = labelOptions(
  59.                             opacity = 0.8
  60.         ),
  61.         popup = ~as.character(paste(HSP_id, '-', HSP)),
  62.         popupOptions = labelOptions(
  63.                             opacity = 0.8
  64.         )
  65. )
  66.  
  67. # It's possible to build own icons with the three built-in functions makeIcon, icons, and iconList
  68. # It's possibly easier to start from the following three libraries:
  69. # - fa: Font Awesome http://fontawesome.io/icons/,
  70. # - glyphicon: Bootstrap Glyphicons https://getbootstrap.com/components/,
  71. # - ion: Ion icons http://ionicons.com/,
  72. # and using similar functions:
  73. # - makeAwesomeIcon
  74. # - awesomeIcons
  75. # - awesomeIconList
  76. #
  77. hsp.icons <- awesomeIcons(
  78.     icon = 'h-square',
  79.     library = 'fa',
  80.     squareMarker = TRUE,
  81.     markerColor = sapply(centres$type, function(x) if(x == 1){ "lightgreen" } else { "lightred" }),
  82.     iconColor = 'white'
  83. )
  84.  
  85. mp %>% addAwesomeMarkers(data = centres,
  86.         lng = ~X_lon, lat = ~Y_lat,
  87. #        color = ~type,
  88.         label = ~as.character(HSP_id),
  89.         labelOptions = labelOptions(
  90.                             opacity = 0.8
  91.         ),
  92.         popup = ~as.character(paste(HSP_id, '-', HSP)),
  93.         popupOptions = labelOptions(
  94.                             opacity = 0.8
  95.         ),
  96.         icon = hsp.icons
  97. )
  98.  
  99.  
  100.  
  101. mp %>% addCircleMarkers(~long, ~lat, label = ...)
  102.  
  103. mp %>% addRectangles()
  104.  
  105. mp %>% addPolygons()
  106.  
  107. mp %>% addLabelOnlyMarkers(~long, ~lat, label = ...)
  108.  
  109. mp %>% addPopups(~long, ~lat, label = ...)
  110.  
  111. mp %>% addLegend()
  112.  
  113. mp %>% addLayersControl(
  114.             baseGroups = c('grp1', 'grp2', ...),
  115.             overlayGroups = c('grp1'),
  116.             options = layersControlOptions(collapsed = FALSE)    
  117. )
  118.  
  119. # -------------------------------------------------------------------------------------------------------------------------------
  120. # # # LET's ADD POLYGONS
  121.  
  122. # read boundaries
  123. shp.path <- 'C:/projects/boundaries/shp'
  124. boundaries <- lapply(c('CCG', 'LAT', 'NHSR', 'CCR', 'CTRY'), function(x) readOGR(shp.path, x))
  125. names(boundaries) <- c('CCG', 'LAT', 'NHSR', 'CCR', 'CTRY')
  126.  
  127. area <- 'CCG'
  128. metric <- 'No. pPCIs'
  129. metric <- 'No. Cases Age > 80'
  130. # y <- get.y.tms(dataset, 'Mean Euroscore', 'CCG_id', tt = c(NA, 'CCG'))
  131. # pct <- FALSE
  132. y <- get.y.tms(dataset, metric, paste0(area, '_id'), pct = TRUE)
  133. pct <- TRUE
  134. y <- merge(y, unique(hospitals[, .(X = get(paste0(area, '_id')), Xo = get(paste0(area, '_ons')), Xn = get(area))]))
  135. bndT <- merge(boundaries[[area]], y, by.x = 'id', by.y = 'Xo')
  136. bnd <- merge(boundaries[[area]], y, by.x = 'id', by.y = 'Xo', all.x = FALSE)
  137. bndT <- merge(bndT[is.na(bndT$Y), 'id'], areas[type == area, .(ons_id, nhs_id, name)], by.x = 'id', by.y = 'ons_id')
  138.  
  139. # bins <- c(0, 10, 20, 50, 100, 200, 500, 1000, Inf)
  140. # pal <- colorBin("YlOrRd", domain = states$density, bins = bins)
  141.  
  142. # mp <- leaflet() %>%
  143. #         setView(-96, 37.8, 4) %>%
  144. #         fitBounds(lng1 = 1.8, lat1 = 49.9, lng2 = -8.3, lat2 = 59.0 ) %>%
  145. #         addTiles('http://{s}.tile.openstreetmap.fr/hot/{z}/{x}/{y}.png')
  146.  
  147. mp <- mp %>%
  148.         addPolygons(data = bndT,
  149.             stroke = TRUE,
  150.             color = "#444444",
  151.             opacity = 1.0,
  152.             weight = 0.6,
  153.             fill = TRUE,
  154.             fillColor = "#E0E0E0",
  155.             fillOpacity = 0.4,
  156.             smoothFactor = 0.5,
  157.             group = 'UK',
  158.             highlightOptions = highlightOptions(
  159.                 color = "red",
  160.                 weight = 1,
  161.                 bringToFront = TRUE
  162.             ),
  163.             label = lapply(paste0(bndT$name, ': <b>NOT supported</b>'), HTML),
  164.             labelOptions = labelOptions(
  165.                 textsize = "12px",
  166.                 direction = "auto",
  167.                 style = list("font-weight" = "normal", padding = "3px 8px")
  168.             )
  169.         )
  170.  
  171. mp <- mp %>%
  172.         addPolygons(data = bnd,
  173.             color = "#444444",
  174.             weight = 1,
  175.             smoothFactor = 0.5,
  176.             opacity = 1.0,
  177.             fillOpacity = 0.5,
  178.             fillColor = ~colorQuantile("YlOrRd", Y)(Y),
  179.             highlightOptions = highlightOptions(
  180.                 color = "white",
  181.                 weight = 3,
  182.                 bringToFront = TRUE
  183.             ),
  184.             label = lapply(
  185.                         paste0(
  186.                             area, ': ', bnd$Xn, '<br/>',
  187.                             metric, ':<b>', if(pct) { paste0(100*bnd$Y, '%') } else {bnd$Y}, '</b>'
  188.                         ),
  189.                     HTML
  190.             ),
  191.             labelOptions = labelOptions(
  192.                 textsize = "15px",
  193.                 direction = "auto",
  194.                 style = list("font-weight" = "normal", padding = "3px 8px")
  195.             )
  196.         )
  197.  
  198. mp <- mp %>%
  199.         addLegend(
  200.             pal = colorBin(
  201.                     "YlOrRd",
  202.                     domain = states$density,
  203.                     bins = bins
  204.             ),
  205.             values = ~density,
  206.             opacity = 0.7,
  207.             title = NULL,
  208.             position = "bottomright"
  209.         )
  210.  
  211. mp
  212.    
  213.    
  214.    
  215. # save map as html
  216. saveWidget(mp, file = 'mapnmae.html')
  217.  
  218. # save map as image: you need mapview and webshot packages, plus phantomJS
  219. mapshot(mp, file = 'mapname.png')
Advertisement