Search code examples
phpapidistancepostal-code

PHP Distance between 2 UK postcodes


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
);
?>  

Solution

  • 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!