library(tidyverse)
library(sf)
library(geojsonsf)
library(leaflet)
library(stringr)
library(readr)

Define paths

path <- "~/OneDrive - University of Bristol/Documents/_dissertation/diss_coding/population"
population <- file.path(path, "population-estimates-2005-2016-2016-ward.geojson")
tab = NA
population <- geojson_sf(population)

population <- st_as_sf(population) 

population_2019 <- population %>%
  filter(mid_year == 2019) %>%
  arrange(ward_2016_name)

tibble::glimpse(population_2019)
## Observations: 34
## Variables: 6
## $ ward_2016_name      <chr> "Ashley", "Avonmouth & Lawrence Weston", "Bedmins…
## $ population_estimate <dbl> 19075, 21408, 12517, 13338, 11415, 11785, 11456, …
## $ mid_year            <chr> "2019", "2019", "2019", "2019", "2019", "2019", "…
## $ ward_2016_code      <chr> "E05010885", "E05010886", "E05010887", "E05010888…
## $ geo_point_2d        <chr> "[51.4683087281,-2.58267455617]", "[51.5073327319…
## $ geometry            <POLYGON [°]> POLYGON ((-2.576109 51.4758..., POLYGON (…
Pop_pal <- colorQuantile("YlOrRd", domain = population_2019$population_estimate, n=5)
Pop_pal_colors <- unique(Pop_pal(sort(population_2019$population_estimate)))
Pop_labs_leg <- quantile(population_2019$population_estimate, seq(0, 1, .2))
Pop_labs_leg <- paste(dplyr::lag(Pop_labs_leg, n= 1L), Pop_labs_leg, sep = " - ")[-1]
Pop_labs <- function(population_2019){
  sprintf("<span style='color: #858585; font: Arial;font-size: 8pt'><strong>Ward:<span style='color: #333333; font: Arial; font-size: 10pt'> %s</strong><br/>
           <span style='color: #858585; font: Arial; font-size: 8pt'><strong>Population Estimate: <span style='color: #333333; font: Arial; font-size: 10pt'>%g </strong>residents<br/>",
          population_2019$ward_2016_name, population_2019$population_estimate) %>% 
    lapply(htmltools::HTML)
}

Pop_lab <- Pop_labs(population_2019)
leaflet(population_2019) %>%
  addTiles(
    urlTemplate = "https://{s}.tile.thunderforest.com/{variant}/{z}/{x}/{y}.png?apikey={apikey}",
    attribution = "&copy; <a href='http://www.thunderforest.com/'>Thunderforest</a>,  &copy; <a href='http://www.openstreetmap.org/copyright'>OpenStreetMap</a>",
    options = tileOptions(variant='transport', apikey = 'fb07784de8604d5cb974f9430e070f00')) %>% 
  addPolygons(
    fillColor = ~Pop_pal(population_estimate),
    weight = 2,
    opacity = 1,
    color = "white",
    dashArray = "3",
    fillOpacity = 0.7,
    highlight = highlightOptions(
      weight = 5,
      color = "#666",
      dashArray = "",
      fillOpacity = 0.7,
      bringToFront = TRUE),
    label = Pop_lab,
    group = "2019 population estimate") %>% 
  addLegend("bottomright",
    colors = Pop_pal_colors,
    labels = Pop_labs_leg,
    title = "Population estimates (in 2019)",
    opacity = 1) %>%
  addLayersControl(
    overlayGroups = "2019 population estimate",
    options = layersControlOptions(collapsed = FALSE)
  )