Using PHP and google Maps Api to work out distance between 2 post codes (UK)
Assuming you are looking for the geographic distance, first you need to get the latitude and longitude of your two postcodes with the Google Maps server-side geocoding services as in the following example:
$url = 'http://maps.google.com/maps/geo?q=EC3M,+UK&output=csv&sensor=false';
$data = @file_get_contents($url);
$result = explode(",", $data);
echo $result[0]; // status code
echo $result[1]; // accuracy
echo $result[2]; // latitude
echo $result[3]; // longitude
Then you can calculate the distance between the coordinates of your two postcodes by using a great-circle distance implementation such as the following:
- Snipplr - Calculate distance between two coordinates in PHP
Note that the server-side geocoding service may only be used in conjunction with displaying results on a Google map; geocoding results without displaying them on a map is prohibited by the Google Maps API Terms of Service License Restrictions.
UPDATE:
If you are looking for the driving distance instead of the geographical distance, note that there is no documented and approved method at the moment to access the Google Maps Directions API via an HTTP request on the server-side.
Nevertheless, an undocumented method that returns a JSON output is the following:
http://maps.google.com/maps/nav?q=from:London%20to:Dover
This will return you the driving directions, along with the total driving distance in JSON format: "meters":122977
.
The format of the q
parameter should be from:xxx%20to:yyy
. Replace xxx and yyy with the start and destination respectively. You can use latitude and a longitude coordinates instead of full addresses:
http://maps.google.com/maps/nav?q=from:51.519894,-0.105667%20to:51.129079,1.306925
Note that not only this is undocumented, but it may also violate the restrictions 10.1 and 10.5 of the Google Maps API Terms and Conditions.
You may also be interesting in checking out the following related articles:
- Stack Overflow: Calculate driving directions using PHP?
- Getting distance using GDirections via URL
- Retrieve driving directions from google maps with server-side HTTP calls and show results with static maps for WAP
- Google Maps and Directions, REST Interface?
PHP Distance between 2 UK postcodes
Here is 1 problem with your code
$url = "http://maps.googleapis.com/maps/api/distancematrix/json?origins=postcode1&destinations=$postcode2&mode=driving&language=en-EN&sensor=false";
needs to be
$url = "http://maps.googleapis.com/maps/api/distancematrix/json?origins=$postcode1&destinations=$postcode2&mode=driving&language=en-EN&sensor=false";
So that the URL is correctly generated
EDIT-------------------------------------------------
Ive just ran this code
$url = "http://maps.googleapis.com/maps/api/distancematrix/json?origins=DN17%202HG&destinations=DN17%202HJ&mode=driving&language=en-EN&sensor=false";
$data = @file_get_contents($url);
$result = json_decode($data, true);
//print_r($result); //outputs the array
$distance = array( // converts the units
"meters" => $result["rows"][0]["elements"][0]["distance"]["value"],
"kilometers" => $result["rows"][0]["elements"][0]["distance"]["value"] / 1000,
"yards" => $result["rows"][0]["elements"][0]["distance"]["value"] * 1.0936133,
"miles" => $result["rows"][0]["elements"][0]["distance"]["value"] * 0.000621371
);
print_r($distance);
and it produced me
Array
(
[meters] => 420
[kilometers] => 0.42
[yards] => 459.317586
[miles] => 0.26097582
)
which is spot on, The problem most likely exists in the postcodes, check that the URL is correct and urlencode
the both the postcodes
ANOTHER EDIT ----------------------------
It might be a bigger problem that I thought...
You need to wrap the end bit of code in a function so that the distance can be calculated in for each user
if (isset($_GET['search'])) {
$userSearch = $_GET['search']; // search for users by username
$query = mysql_query("SELECT username, postcode, user_id FROM users WHERE username LIKE '%$userSearch%'");
$rowcount = mysql_num_rows($query);
if ($userSearch == "") {
} else {
if ($rowcount != 0) {
while ($row = mysql_fetch_assoc($query)) {
$username = $row['username'];
$postcode = $row['postcode'];
$user_id = $row['user_id'];
$sql = mysql_query("SELECT postcode FROM users WHERE user_id = $user_id");
$results = mysql_fetch_assoc($sql);
echo $results['postcode'];
$distance = getDistance($user_data['postcode'], $postcode);
//im not sure where the $user_data comes from but it was in your original code
echo '<a href="' . $username . '">' . $username . '</a> ' . $postcode . ' is : ' . number_format($distance["miles"], 2) . " Mile(s) away" . '<br/>'; // returns results
}
} else {
echo "No user found";
}
}
}
function getDistance($start, $end) {
// Google Map API which returns the distance between 2 postcodes
$postcode1 = preg_replace('/\s+/', '', $start);
$postcode2 = preg_replace('/\s+/', '', $end);
$result = array();
$url = "http://maps.googleapis.com/maps/api/distancematrix/json?origins=$postcode1&destinations=$postcode2&mode=driving&language=en-EN&sensor=false";
$data = @file_get_contents($url);
$result = json_decode($data, true);
//print_r($result); //outputs the array
return array( // converts the units
"meters" => $result["rows"][0]["elements"][0]["distance"]["value"],
"kilometers" => $result["rows"][0]["elements"][0]["distance"]["value"] / 1000,
"yards" => $result["rows"][0]["elements"][0]["distance"]["value"] * 1.0936133,
"miles" => $result["rows"][0]["elements"][0]["distance"]["value"] * 0.000621371
);
}
I really must point out that using mysql_* is not such a good thing, I would recommend looking into mysqli or PDO both which have much safer interface. If you must use the queries in this way make sure you escape the data or you could become a victim of SQL injection!
Using PHP and google Maps Api to work out distance between 2 latitude and longitude
Calculate distance between two points in google maps V3
I think you might be after something like this which has a few good answers.
Related Topics
Upload 1Gb Files Using Chunking in PHP
Laravel App Stopped Working After Upgrading to PHP 8
Convert All Types of Smart Quotes with PHP
PHP Sentence Boundaries Detection
PHP JSON Encode - Malformed Utf-8 Characters, Possibly Incorrectly Encoded
How to Put PHP Inside JavaScript
PHP Get Url of Redirect from Source Url
File_Get_Contents Returns 403 Forbidden
Destroy or Unset Session When User Close the Browser Without Clicking on Logout
Mysql_Real_Escape_String VS Addslashes
How to Sort an Array of Utf-8 Strings
Instantiate a Class with or Without Parentheses
Can You Add an If Statement in Order By
PHP Session Side-Effect Warning with Global Variables as a Source of Data
Pkill -F Doesn't Work for Process Killing
How to Protect from Downloading a Video from a Site
How to Use "Dependency Injection" in Simple PHP Functions, and Should I Bother