PHP postcode distance calculation program

How to calculate the distance between two UK postcodes using PHP

First of all you need this database: UK Postcodes Database.

It lists the first bit of around 3000 postcodes,  Royal Mail will be able to provide a more detailed postcode database.

The database is set up like this
Pcode,  Grid_N,  Grid_E
BD1     416300   433300
LE7     463000   309300

The distance is calculated by using pythagoras to find the hypotenuse of a triangle drawn between the postcode grid references.

This code below is to be placed in one php file, it will calculate the distance between the two postcodes specified in the function below:

echo calc_postcode_seperation('LE7','BD1');

There are a large number of things you can do with this, one thing I've done is create a script which finds all the postcodes within a certain radius.  A good example is to be found on the autotrader.co.uk website which searches for cars for sale within a certain distance from your area.

Here's the script:

// Connect to the database server

$dbcnx = mysql_connect("localhost",

"user", "pass");

if (!$dbcnx) {

echo( "

Unable to connect to the " .

"database server at this time (this is a host connect problem).

" );

exit();

}

// Select the database

if (! mysql_select_db("dbase_name", $dbcnx) ) {

echo( "

Unable to locate the " .

"database at this time(this is a dbconnect problem).

" );

exit();

}

function calc_postcode_seperation($pcodeA,$pcodeB)

{

// PCODE A

$result=mysql_query("SELECT * FROM postcodes WHERE Pcode='$pcodeA' LIMIT 1");

$row=mysql_fetch_array($result);

$gridn[0]=$row[Grid_N];

$gride[0]=$row[Grid_E];

// PCODE B
$result=mysql_query("SELECT * FROM postcodes WHERE Pcode='$pcodeB' LIMIT 1");

$row=mysql_fetch_array($result);

$gridn[1]=$row[Grid_N];

$gride[1]=$row[Grid_E];

// TAKE GRID REFS FROM EACH OTHER.

$distance_n=$gridn[0]-$gridn[1];

$distance_e=$gride[0]-$gride[1];

// CALCULATE THE DISTANCE BETWEEN THE TWO POINTS

$hypot=sqrt(($distance_n*$distance_n)+($distance_e*$distance_e));

$text.='Distance between '.$pcodeA.' and '.$pcodeB.' is: '.round($hypot/1000,2).'kms';

return $text;

}

echo calc_postcode_seperation('LE7','BD1');

?>



You should get something like:

Distance between LE7 and BD1 is: 132.5kms

I hope this provides a nice postcode solution,  it's certainly very useful in many different e-commerce and billing situations.

Hugh Newsome



 HOME
 THE COMPANY
 WEB MARKETING
 DESIGN AGENCY
 TESTIMONIALS
 TUTORIALS
1 - YOUR FIRST PHP CODE
2 - USING VARIABLES
PHP POSTCODE SCRIPT
Distance Between Postcodes
 CONTACT
 WEB DESIGN LINK EXCHANGE
 CURRENCY RSS FEED

©Sloomedia 2004, Web Site Design Nottingham, UK - email:info@sloomedia.com