PHP 2个英国邮政编码之间的距离

时间:2014-03-13 18:01:54

标签: php api distance postal-code

我已经在这上面好了3个星期了,试图搞清楚。这是我试图为uni项目建立的网站的一部分。 用户注册到我的网站,提供一些详细信息(包括他们的邮政编码)然后,一旦您注册,您的想法是您可以通过用户名搜索其他用户,它将显示找到的用户名列表,其中包含您注册的邮政编码和他们的。我使用了相同的谷歌api,它可以在另一个页面上正常工作,但由于某种原因,我不能让它在这里工作。在代码中的某个点,变量$ distance不返回任何内容。请你能帮忙,我真的失去了与此共存的意愿。

非常感谢,任何帮助将不胜感激!

最高

这是我的代码:

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

1 个答案:

答案 0 :(得分:3)

以下是您的代码的1个问题

$url = "http://maps.googleapis.com/maps/api/distancematrix/json?origins=postcode1&destinations=$postcode2&mode=driving&language=en-EN&sensor=false";

需要

$url = "http://maps.googleapis.com/maps/api/distancematrix/json?origins=$postcode1&destinations=$postcode2&mode=driving&language=en-EN&sensor=false";

以便正确生成URL

EDIT ---------------------------------------------- ---

我刚刚运行了这段代码

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

它让我产生了

Array
(
    [meters] => 420
    [kilometers] => 0.42
    [yards] => 459.317586
    [miles] => 0.26097582
)

哪个是现货,问题很可能存在于邮政编码中,检查网址是否正确以及urlencode两个邮政编码

另一个编辑----------------------------

我认为这可能是一个更大的问题......

您需要在函数中包含代码的结束位,以便可以为每个用户计算距离

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

我真的必须指出,使用mysql_ *并不是一件好事,我建议调查mysqli或PDO两者都有更安全的界面。如果您必须以这种方式使用查询,请确保您转义数据,否则您可能成为SQL注入的受害者!