1

In my php application I want to get the nearest postal code of the given post code. That means I enter a post code as 680721 I want to get the nearest post code of this from my database.

How can I do this?

This is the table I used for store postal codes. enter image description here

enter image description here

Here varpin is the postal code field.

Ariful Islam
  • 7,639
  • 7
  • 36
  • 54
Kichu
  • 3,284
  • 15
  • 69
  • 135

1 Answers1

3

Having said all this, a quick browse through the “External Links” on the UK Postcodes Wikipedia entry, and I quickly found an article by Paul Jenkins entitled UK Post Code Distance Calculation in PHP, which is fantastic, you can even download it here (uk_postcode_calc.zip). After a short examination it seems this does exactly what it says on the tin, and simply calculates the distance. However, with a quick google for php distance calculation, you can quickly find that there are more refined equivalents of the distance calculation. I thought it might be a good idea to use one of those instead. After a bit of tweaking, here’s what I came up with in the end:

function distance($lat1, $lon1, $lat2, $lon2, $u=’1′) {
$u=strtolower($u);
if ($u == ‘k’) { $u=1.609344; } // kilometers
elseif ($u == ‘n’) { $u=0.8684; } // nautical miles
elseif ($u == ‘m’) { $u=1; } // statute miles (default)
$d=sin(deg2rad($lat1))*sin(deg2rad($lat2))+cos(deg2rad($lat1))*cos(deg2rad($lat2))*cos(deg2rad($lon1-$lon2));
$d=rad2deg(acos($d));
$d=$d*60*1.1515;
$d=($d*$u); // apply unit
$d=round($d); // optional
return $d;
}

So, that’s the hard parts done (database and maths), next is simply a case of using this information to “find the closest” from the postcode we input to an array of postcodes we supply… To find the “closest” postcode, effectively what we’re trying to do is find the “shortest” distance between the postcodes, or, simply the smallest number in the results, assuming we put the results into an array with the key as the postcode and the distance as the value. All we have to do is create a simple script that will find the smallest number in a given array, then return the appropriate key. Simple!

function closest ($needle,$haystack) {
if (!$needle || !$haystack) { return; }
if (!is_array($haystack)) { return; }
$smallest=min($haystack); //smallest value
foreach ($haystack as $key => $val) {
if ($val == $smallest) { return $key; }
}
}

The above script does exactly what we want, using the “min” function we can quickly work out what we need to return. The only task left is to bind all this together, we need to create two functions that will: Get the distance using the postcode to get the longitude and latitude from the database. Create an array with the postcodes as the keys, and the distance as the values. Very simple! Function 1, Postcode Distance

function postcode_distance ($from,$to) {
// Settings for if you have a different database structure
$table=’postcodes_uk’;
$lat=’lat’;
$lon=’lon’;
$postcode=’postcode’;
// This is a check to ensure we have a database connection
if (!@mysql_query(‘SELECT 0′)) { return; }
// Simple regex to grab the first part of the postcode
preg_match(‘/[A-Z]{1,2}[0-9R][0-9A-Z]?/’,strtoupper($from),$match);
$one=$match[0];
preg_match(‘/[A-Z]{1,2}[0-9R][0-9A-Z]?/’,strtoupper($to),$match);
$two=$match[0];
$sql = “SELECT `$lat`, `$lon` FROM `$table` WHERE `$postcode`=’$one’”;
$query = mysql_query($sql);
$one = mysql_fetch_row($query);
$sql = “SELECT `$lat`, `$lon` FROM `$table` WHERE `$postcode`=’$two’”;
$query = mysql_query($sql);
$two = mysql_fetch_row($query);
$distance = distance($one[0], $one[1], $two[0], $two[1]);
// For debug only…
//echo “The distance between postcode: $from and postcode: $to is $distance miles\n”;
return $distance;
}
Function 2, Postcode Closest
function postcode_closest ($needle,$haystack) {
if (!$needle || !$haystack) { return; }
if (!is_array($haystack)) { return; }
foreach ($haystack as $postcode) {
$results[$postcode]=postcode_distance($needle,$postcode);
}
return closest($needle,$results);
}

So, with that done, place the 4 above functions into a file such as “postcode.php”, ready for use in the real world… Test case:

<?php
include_once(‘postcode.php’);
if ($_POST) {
include_once(‘db.php’);
$postcodes=array(‘TF9 9BA’,'ST4 3NP’);
$input=strtoupper($_POST['postcode']);
$closest=postcode_closest($input,$postcodes);
}
if (isset($closest)) {
echo “The closest postcode is: $closest”;
}
?>
<form action=”" method=”post”>
Postcode: <input name=”postcode” maxlength=”9″ /><br />
<input type=”submit” />
</form>

You can download this script here: postcode_search.phps Note: In the above test case, I have a “db.php” file which contains my database details and starts a database connection. I suggest you do the same. Ensure you have your database populated, you should be able to use Paul Jenkins’s UK Postcode csv, allowing you to use your own table structure. Well, that’s all folks, I can now use this script to provide any locations that match the “closest” postcode.

Code Lღver
  • 15,573
  • 16
  • 56
  • 75
  • 1
    If you're working with UK postcodes, and can't afford the Post Offices PAF for your postcode data... you might be interested to know that the Irdnance Survey provide a free download of Great Britain postcode data under an open license at https://www.ordnancesurvey.co.uk/oswebsite/products/code-point-open/index.html - You will need to convert northings/eastings to WGS84 lat/long, but there's plenty of libraries available to help with that – Mark Baker Dec 08 '11 at 08:14
  • 1
    But my this code will work for all countries, not only for Great Britain, this is a master code. – Code Lღver Dec 08 '11 at 08:30
  • Your code will work for all countries - but your postcode data still needs to exist first to give you lat/long for postcodes... you mentioned Paul Jenkins's CSV, but the Post Office PAF or Ordnance Survey datasets are rather more definitive. – Mark Baker Dec 08 '11 at 08:46
  • PS - Northern Ireland postcode data is also available from OSNI, though not as up-to-date as the OS data for GB – Mark Baker Dec 08 '11 at 08:50
  • 1
    Yes, as define in question, the user has the database of postal codes – Code Lღver Dec 08 '11 at 09:10