Edit this page

< back to recipes

Sometimes you have a set of addresses but no way of mapping them. Helpfully, the Office for National Statistics’ Open Geography Portal provides the centroids for all UK postcodes. This recipe shows you how to query the Portal’s API and retrieve the centroid coordinates for a given set of postcodes.

Ingredients

Instructions

  1. Load the necessary R packages.
library(tidyverse) ; library(jsonlite) ; library(sf)
  1. Load your postcodes as a character vector.
addresses <- c("WA14 4AP", "M33 1LH", "WA14 5SE", "M33 4JS", "M41 9WG")
  1. Retrieve the coordinates for the centroid of each postcode.
postcodes <- fromJSON(paste0("https://ons-inspire.esriuk.com/arcgis/rest/services/Postcodes/ONS_Postcode_Directory_Latest_Centroids/MapServer/0/query?where=", URLencode(paste0("pcds IN (", paste(shQuote(addresses), collapse = ", "), ")")), "&outFields=pcds,lat,long&outSR=4326&f=json"), flatten = TRUE) %>% 
  pluck("features") %>% 
  as_tibble() %>% 
  select(postcode = attributes.pcds,
         lon = attributes.long,
         lat = attributes.lat)
  1. Write as a CSV.
write_csv(postcodes, "postcodes.csv")
  1. Write as a GeoJSON.
postcodes %>% 
  st_as_sf(crs = 4326, coords = c("lon", "lat")) %>% 
  st_write("postcodes.geojson")