The API

How to use the API

http://postcod.es/postcode/<LAT>/<LON>

This is the URL for looking up a postcode. Hitting that URL with actual lat/lon values results in a simple JSON response:

{'Postcode':'XXX XXX'}

If you are calling the API from server-side code, then you're good to go. If you're calling from javascript, then you need to use JSONP to allow you to make a request to a seperate domain. Check out the examples for more details.

Examples

This example uses jQuery to make a request for a postcode:

$.ajax({
  dataType: 'jsonp',
  data: "",
  jsonp: 'callback',
  url: '/postcode/' + lat + '/' + lng,
  success: function(data) {
   console.log('Got postcode', data.Postcode);
  }

Obviously you need to set lat and lon to something sensible :)

Quite often you'll want to detect the user's current location, and then use those co-ords to get the postcode. This example shows a basic solution:

function showMap(pos) {
  $.ajax({
    dataType: 'jsonp',
    data: "",
    jsonp: 'callback',
    url: '/postcode/' + pos.lat + '/' + pos.lng,
    success: function(data) {
     console.log('Got postcode', data.Postcode);
  } }

// One-shot position request.
navigator.geolocation.getCurrentPosition(showMap);

This example uses the Geolocation API specification to make a "one-shot" attempt to get the current location. When the location is returned, showMap is called which in this case passes the lat/lon to the postcodes API. For more information check out the link above, where various examples are provided to probe for the current location. You might also want to have a look at the Dive into HTML5 - Geolocation chapter, which provides some good information and introduces geo.js for better geolocation handling on mobile browsers.

If you want to use mapping, I'd recommend you check out the awesome Leaflet javascript library for interactive maps, which includes support for geo-location along with many other things.