How can I get a list of postcodes (GB) given a postcode (or coordinates) and a radius?

2.9k views Asked by At

There are plenty of articles on this subject but I couldn't find any that suits my needs. The only thing I need is to get a list of postcodes within a x miles radius of another postcode. I don't have a postcode database and although there is a free service that does exactly what I need (http://postcodes.io/), it does have a deal breaker limitation (max radius = 2km) so I cant really use it.

I think maybe I need to look at google maps API in more detail, I believe it might provide what I need but it's not clear from the documentation plus it's very much focused in maps (which I don't care about for now). If anyone could shed some light I would greatly appreciate.

This is for a C# project so any useful libraries are welcome.

2

There are 2 answers

0
Phillip On BEST ANSWER

Download a database of postcodes, e.g. this one or this one. If you have high accuracy and completeness requirements on the data, consider buying access to the official database. You can retrieve missing coordinates using Google's GeoCoding API. If you need to resolve more codes than the allowed daily free quota, I would recommend to buy a larger quota, it's quite cheap. Google covers this in the documentation.

Once you have the database, either store it in a SQL database with Geo extensions, e.g. Postgis, and then do the lookups using SQL, or preprocess it into a form that allows fast lookup of adjacent postcodes. In my experience, the best option for lookup by postcode is to add some overhead and store a hashmap of postcode → [ (postcode, distance), (postcode, distance), .. ] relations, with the lists containing every postcode for the largest radius you're ever going to look up. That is, don't use tree traversal in your searches. For the coordinate to postcodes relation you can either use a sophisticated data structure for spatial data, like a BSP tree, or keep it simple and use a coarse 2D grid structure, where each node contains all post codes that are within the associated square within the grid.

0
C Blanchard On

Just to complement the accepted answer, postcodes.io also provides a pg_dump of the dataset it uses (requires Postgresql with Postgis enabled).

Once you download and unpack the file, a Postgresql restore procedure e.g. $ cat postcodeiodb.sql | psql postcodesiodb is all you need to import the entire dataset. No additional import scripts required. Furthermore the pg_dump will create all the necessary schemas & indexes for you.

The project keeps a pointer to the latest dataset here: https://github.com/ideal-postcodes/postcodes.io/blob/master/latest

Disclaimer: I maintain postcodes.io