I've been on this for a good 3 weeks now, trying to figure it out. This is part of a website I am trying to build for a project at uni. The users register to my website giving a few details (including their postcode) then once you're registered the idea is that you can search for other users by username and it will display a list of usernames found with the distance between your registered postcode and theirs. I have used the same google api which works fine on another page but for some reason, i cannot get it to work on here. At some point in the code, the variable $distance does not return anything. Please can you help, I am really losing the will to live with this.
Thanks a lot in advance, any help will be greatly appreciated!
Max
This is my code:
<form action="" method="get">
<ul>
<li>
<label>
<h4>Type in a username and hit search</h4>
</label>
<input <input type="text" name="search"/>
<input type="submit" name="submit" value="Search"/>
</li>
</ul>
</form>
<?php
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'];
echo '<a href="' . $username . '">' . $username . '</a> ' . $postcode . ' is : ' . number_format($distance["miles"], 2) . " Mile(s) away" . '<br/>'; // returns results
}
} else {
echo "No user found";
}
}
}
// Google Map API which returns the distance between 2 postcodes
$postcode1 = preg_replace('/\s+/', '', $user_data['postcode']);
$postcode2 = preg_replace('/\s+/', '', $postcode);
$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
$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
);
?>