9  UK Postcode Maps

Author

Chrissy h Roberts

9.1 Background

This is a basic tutorial on how to load shapefiles and geopoints to a leaflet map.

There is a lot more detailed information here [https://rstudio.github.io/leaflet/](https://rstudio.github.io/leaflet/)

The example is hopefully useful as it uses UK postcode and district shapefiles, which are commonly useful for a variety of purposes.

UK Postcode data can be found here

https://www.freemaptools.com/map-tools.htm

UK district shapefiles are available here

https://www.ordnancesurvey.co.uk/opendatadownload/products.html

9.2 Libraries

library(tidyverse)
── Attaching core tidyverse packages ──────────────────────── tidyverse 2.0.0 ──
✔ dplyr     1.1.4     ✔ readr     2.1.5
✔ forcats   1.0.0     ✔ stringr   1.5.1
✔ ggplot2   3.5.1     ✔ tibble    3.2.1
✔ lubridate 1.9.4     ✔ tidyr     1.3.1
✔ purrr     1.0.4     
── Conflicts ────────────────────────────────────────── tidyverse_conflicts() ──
✖ dplyr::filter() masks stats::filter()
✖ dplyr::lag()    masks stats::lag()
ℹ Use the conflicted package (<http://conflicted.r-lib.org/>) to force all conflicts to become errors
library(sf)
Linking to GEOS 3.13.0, GDAL 3.8.5, PROJ 9.5.1; sf_use_s2() is TRUE
library(knitr)
library(leaflet)

9.3 Data

9.3.1 Create a folder to house data

if(!dir.exists("data/ukpostcodes"))(dir.create("data/ukpostcodes"))
[1] TRUE
system("rm -rf data/ukpostcodes/*")

9.4 Download a list of UK postcodes and gps locations

download.file(url = "https://data.freemaptools.com/download/full-uk-postcodes/ukpostcodes.zip",destfile =paste("data/ukpostcodes/ukpostcodes.zip"))

system ("unzip data/ukpostcodes/ukpostcodes.zip -d data/ukpostcodes/")

9.5 Download a list of UK district shapefiles

# set a timeout proportional to the size of the dataset and the speed of the connection
options(timeout=300)

download.file(url = "https://api.os.uk/downloads/v1/products/BoundaryLine/downloads?area=GB&format=ESRI%C2%AE+Shapefile&redirect",destfile =paste("data/ukpostcodes/bdline_essh_gb.zip"))

system ("unzip data/ukpostcodes/bdline_essh_gb.zip -d data/ukpostcodes/")

9.6 Read Postcode data

ukpostcodes <- read_csv("data/ukpostcodes/ukpostcodes.csv")
Rows: 1804112 Columns: 4
── Column specification ────────────────────────────────────────────────────────
Delimiter: ","
chr (1): postcode
dbl (3): id, latitude, longitude

ℹ Use `spec()` to retrieve the full column specification for this data.
ℹ Specify the column types or set `show_col_types = FALSE` to quiet this message.

9.7 Make a small sample of all postcodes

sample<-ukpostcodes[sample(1:nrow(ukpostcodes),size = 100),] %>% 
  mutate(
    latitude = as.numeric(latitude),
    longitude = as.numeric(longitude)
  )
head(sample)
# A tibble: 6 × 4
       id postcode latitude longitude
    <dbl> <chr>       <dbl>     <dbl>
1  325804 SN25 4AF     51.6    -1.78 
2 1121234 GL51 0QN     51.9    -2.12 
3 1669962 B63 4RZ      52.4    -2.06 
4  643799 NW1 1LL      51.5    -0.131
5  690786 NN15 5QA     52.4    -0.683
6  908834 LE5 5FE      52.6    -1.10 

9.8 Read in shapefiles to a map

map = read_sf("data/ukpostcodes/Data/GB/county_region.dbf")
mapproj <- st_transform(map, st_crs("+proj=longlat +init=epsg:4326 +ellps=WGS84 +datum=WGS84 +no_defs"))
Warning in CPL_crs_from_input(x): GDAL Message 1: +init=epsg:XXXX syntax is
deprecated. It might return a CRS with a non-EPSG compliant axis order.
leaflet(mapproj) %>% 
    addTiles() %>% 
  addMeasure(primaryLengthUnit="kilometers", secondaryLengthUnit="meters")  %>%
  addScaleBar(options = c(imperial = FALSE)) %>%  
  addPolygons(color = "green",label = mapproj$NAME) %>% 
  addCircleMarkers(lng = sample$longitude,lat = sample$latitude,label = sample$postcode,radius = 0.3)