dealing with postcodes and if i cover them on website

Joined
12 Feb 2006
Posts
17,651
Location
Surrey
i'd like to add something to a site that first asks for the users postcode, and then tries to work out where they are and if we cover them. any ideas on something that'll do this or how easy it'd be to make this in php/mysql?
 
Use Google maps API to generate a Lat and Lng from the imputed postcode.

Then use the the distance finder to calculate the distance form that post code to your postcode.

Don't use Pythagorus as obviously the world isn't flat. Use the Great Circle Distance calculator instead. http://en.wikipedia.org/wiki/Great-circle_distance


Download John Gardeners PHPpostcode formatter, this will check and return postcodes in the correct format.

http://www.braemoor.co.uk/software/postcodes.shtml

I did one a couple of months back. I've hacked together this code, it is untested so there might be some bugs but it is roughly what you want.


Code:
	<div style="width: 350px; margin:0 auto;" id="content">	
			<div id="post_wrapper" >
		
			
			
																							  
				<form action="" method="get">
					<fieldset>
						<legend>Enter your postcode</legend>					
					
						<input type="text" name="postcode" value="" action=""> 						
						<input type="submit" value="Submit" name="submit">
					</fieldset>
				</form>
				
					
	
			</div>
			</div>

<?php

// INCLUDE POSTCODE CHECKER

include 'phppostcode.php';

// ENTER THE LAT & LNG OF YOUR POSTCODE HERE. MAKE SURE YOU GET THEM THE CORRECT WAY ROUND

$lat1 = '';
$lng1 = '';

// GOOGLE API KEY

$mykey = 'ENTER YOUR GOOGLE API KEY HERE';



// CHECK AND SEE IF ANYTHING HAS BEE SUBMIT AND IF SO CHECK IT
	
	 if (isset($_GET['submit'])) : 
	
		$postcode = $_GET['postcode']; 

		
		if(!checkPostcode($postcode)) {
			
			echo "Please enter a valid Postcode or Address";

		} else { 



// GET LAT & LNG FROM GOOGLE

$geocode = file_get_contents ("http://maps.google.co.uk/maps/geo?q=" . urlencode($postcode) . "&output=json&key=".$myKey);
			$output = json_decode($geocode);
	
			$lat2 = $output->Placemark[0]->Point->coordinates[1];
			$lng2 = $output->Placemark[0]->Point->coordinates[0];
					

// FIND DISTANCE BETWEEN THEIR POSTCODE AND OURS

$theta = $lon1 - $lon2; 
$dist = sin(deg2rad($lat1)) * sin(deg2rad($lat2)) +  cos(deg2rad($lat1)) * cos(deg2rad($lat2)) * cos(deg2rad($theta)); 
$dist = acos($dist); 
$dist = rad2deg($dist); 

// CONVERT TO MILES AND ECHO BACK

$miles = $dist * 60 * 1.1515;

echo 'Your are ' . $miles . ' miles away from us.';

}

endif;

?>
 
Unfortunately that doesn't take into account rivers. I am less than two miles in a straight line from a place that is a 35 mile drive. If you are going to use the Google API, why not let it get the directions for you and use that distance.

As far the earth being flat, it will give less error inside the UK than that caused by roundabouts.
 
Back
Top Bottom