1

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
);
?>  
PtiSinge
  • 25
  • 2
  • 6
  • 1
    What's in `$data` ? Have you manually verified the query url works? – Alex K. Mar 13 '14 at 18:13
  • If I type Alex (for example) in the search field and var_dump($data); I get: Alex LU6 4QP is : 0.00 Mile(s) away string(246) "{ "destination_addresses" : [ "" ], "origin_addresses" : [ "Luton LU2 0LG, UK" ], "rows" : [ { "elements" : [ { "status" : "NOT_FOUND" } ] } ], "status" : "OK" } " – PtiSinge Mar 13 '14 at 18:22
  • $result gives this: Alex LU6 4QP is : 0.00 Mile(s) away array(4) { ["destination_addresses"]=> array(1) { [0]=> string(0) "" } ["origin_addresses"]=> array(1) { [0]=> string(17) "Luton LU2 0LG, UK" } ["rows"]=> array(1) { [0]=> array(1) { ["elements"]=> array(1) { [0]=> array(1) { ["status"]=> string(9) "NOT_FOUND" } } } } ["status"]=> string(2) "OK" } – PtiSinge Mar 13 '14 at 18:24
  • when you are testing, does the print_r($result), thats commented out, show the correct array? – mic Mar 13 '14 at 18:24
  • well, print_r($result) shows this... Array ( [destination_addresses] => Array ( [0] => ) [origin_addresses] => Array ( [0] => Luton LU2 0LG, UK ) [rows] => Array ( [0] => Array ( [elements] => Array ( [0] => Array ( [status] => NOT_FOUND ) ) ) ) [status] => OK ) – PtiSinge Mar 13 '14 at 18:26
  • What do you get when you echo `$url`? – Samsquanch Mar 13 '14 at 18:28
  • Ok that shows its not finding the address, what is the $url that is created? – mic Mar 13 '14 at 18:28
  • 1
    spotted ur problem :) u are missing a $ before postcode1 in ur url – mic Mar 13 '14 at 18:29

1 Answers1

3

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!

mic
  • 1,251
  • 2
  • 15
  • 33
  • @max82fr see above changes – mic Mar 13 '14 at 18:59
  • @max82fr check out my changes to the answer – mic Mar 13 '14 at 19:32
  • OMG! You fixed it!!! Genius!! THANK YOU SO MUCH!!! How do I give you a green tick to say thank you??? – PtiSinge Mar 13 '14 at 19:36
  • not a problem, glad i could help :) thanks for the tick... I actually didn't know you could do that with google maps API so thanks for your code as well :P – mic Mar 13 '14 at 19:37
  • Although I just realised that if I type a letter in the search box which returns more than one user, the distance for all users outputs as 0.00 Miles – PtiSinge Mar 13 '14 at 19:39
  • Actually I've just realised it doesn't. Work for the first user in my database. But If I type the full username of the second user, stored in the DB, the distance outputs 0.00 – PtiSinge Mar 13 '14 at 19:43
  • Im not sure about where the $user_data['postcode'] comes from, if that value is not being correct set somewhere it could be what is causing the problem. You also need to echo out all the data in the while loop, limit it to 10 users or something so you have not got too much data deal with. Then you can make sure the data is correctly being passed to the getDistance function. – mic Mar 13 '14 at 19:49
  • $user_data['postcode'] comes from the logged_in function which gets run from the init.php at the beginning of every pages. if the user is logged in, a few things are stored (including the postcode). see the init.php file > http://pastebin.com/YjfPhngR – PtiSinge Mar 13 '14 at 20:07
  • After moving bits and pieces around, it all seems to be working now!! THNKS so much Mic!! – PtiSinge Mar 14 '14 at 08:50