Postcode and Geolocation API for the UK
Published:
When I work with UK geographical data, I often need to extract geolocation information for postcodes. A handy way to do this in R is the geocode function from the ggmap package, which returns latitude and longitude via the Google Maps API. That’s great for plotting data points, but it tells you nothing about UK-specific administrative divisions.
I got fed up of merging my list of postcodes with a long list of corresponding wards and the like, so I went looking for a smarter approach.
That’s how I came across postcodes.io: free, open source, and built entirely on open data. It’s an API that geolocates UK postcodes and returns extra administrative information, and the full documentation covers the many available options. The geographic fields you can pull include:
- Postcode
- Eastings
- Northings
- Strategic Health Authority
- County
- District
- Ward
- Longitude
- Latitude
- Westminster Parliamentary Constituency
- European Electoral Region (EER)
- Primary Care Trust (PCT)
- Parish (England) / community (Wales)
- LSOA
- MSOA
- CCG
- NUTS
- ONS/GSS Codes
Since I do most of my analyses in R, I wrote a set of wrapper functions around the API. The development version of the PostcodesioR package is on GitHub, with documentation here. It doesn’t yet support every optional argument, but it should do the job in most cases. There’s also a reference manual here.
Here’s a mini-vignette (more to follow) showing how to look up a postcode, turn the result into a data frame, and build an interactive map with leaflet: The code above produces a data frame with the key information:
> glimpse(pc_df)
Observations: 1
Variables: 28
$ postcode <fctr> EC1Y 8LX
$ quality <int> 1
$ eastings <int> 532544
$ northings <int> 182128
$ country <fctr> England
$ nhs_ha <fctr> London
$ longitude <dbl> -0.09092237
$ latitude <dbl> 51.52252
$ parliamentary_constituency <fctr> Islington South and Finsbury
$ european_electoral_region <fctr> London
$ primary_care_trust <fctr> Islington
$ region <fctr> London
$ lsoa <fctr> Islington 023D
$ msoa <fctr> Islington 023
$ incode <fctr> 8LX
$ outcode <fctr> EC1Y
$ admin_district <fctr> Islington
$ parish <fctr> Islington, unparished area
$ admin_county <lgl> NA
$ admin_ward <fctr> Bunhill
$ ccg <fctr> NHS Islington
$ nuts <fctr> Haringey and Islington
$ admin_district <fctr> E09000019
$ admin_county <fctr> E99999999
$ admin_ward <fctr> E05000367
$ parish <fctr> E43000209
$ ccg <fctr> E38000088
$ nuts <fctr> UKI43
and an interactive map showing the geocoded postcode as a blue dot:
