Converting eastings and northings to latitudes and longitudes in Ruby

23 January 2013

It’s a perennial problem. You’ve got some geodata from a council and you want to put it on a web map. But council systems often serve up Ordnance Survey eastings and northings for the UK rather than the globally useful latitudes and longitudes that most web-based tools and apps use.

Here’s how I’ve converted these coordinates for Sutton Open Maps. There are dozens of alternatives (try searching GitHub for “eastings northings”) so feel free to recommend your favourites in the comments.

My source data is in CSV files and I run it through an importer script to get it into my database. I could do the coordinate conversion in the importer but as I like to republish the CSV files for other people I’ve decided that I need a script that reads a CSV file and outputs a new CSV file with extra columns for the latitudes and longitudes.

For the raw conversion I’m using the OSGB36 Conversion Tools module by Andrew Sprinz for Lambeth Council. It’s great that Lambeth is helping others by opening up its code.

Wrapped around that is my own en2latlon.rb script to convert eastings and northings to latitudes and longitudes. This is run from the command line like this:

$ ruby en2latlon.rb infile.csv > outfile.csv

At the moment my script is hard-coded to search for the eastings and northings columns labelled as “X” and “Y” in the header row. If this doesn’t match your data you could just change them, modify the script to search for multiple possible headings or allow the user to specify them as the command line parameters ARGV[1] and ARGV[2]. (If you’re doing anything more sophisticated than that with command line parameters, use the OptionParser module rather than hack it yourself.)

Many of the Ruby scripts I’ve seen for coordinate conversion are based on the fineĀ PHPcoord PHP package. But there’s one gotcha — ensure that yours doesn’t just convert the coordinates themselves but also remaps the points from the OSGB 36 datum onto the WGS 84 datum used by most web mapping tools. If your script doesn’t do that you may find that all your points are a few tens of metres out.

Adrian Short works to get people the information they need, when they need it, in a way that they can understand.

adrian@adrianshort.co.uk     @adrianshort