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

两个英国邮政编码之间的PHP距离,php,api,distance,postal-code,Php,Api,Distance,Postal Code,我已经在这上面呆了三个星期了,想弄明白。这是一个网站的一部分,我正试图建立一个项目在大学。 用户注册到我的网站,提供一些详细信息(包括他们的邮政编码),然后一旦你注册,你就可以通过用户名搜索其他用户,它将显示一个用户名列表,其中包含注册的邮政编码和他们的邮政编码之间的距离。我使用了相同的GoogleAPI,它可以在另一个页面上正常工作,但由于某些原因,我无法在这里使用它。在代码中的某个点上,变量$distance不会返回任何内容。请你帮帮我,我真的失去了忍受这一切的意志 非常感谢您的帮助 马克斯

我已经在这上面呆了三个星期了,想弄明白。这是一个网站的一部分,我正试图建立一个项目在大学。 用户注册到我的网站,提供一些详细信息(包括他们的邮政编码),然后一旦你注册,你就可以通过用户名搜索其他用户,它将显示一个用户名列表,其中包含注册的邮政编码和他们的邮政编码之间的距离。我使用了相同的GoogleAPI,它可以在另一个页面上正常工作,但由于某些原因,我无法在这里使用它。在代码中的某个点上,变量$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
);
?>  

  • 键入用户名并点击搜索
    您的代码有一个问题

    $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

    编辑-------------------------------------------------

    我刚刚运行了这个代码

    $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
    )
    
    如果正确,问题很可能存在于邮政编码中,请检查URL是否正确,以及
    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
        );
    }
    
    if(isset($\u GET['search'])){
    $userSearch=$\u GET['search'];//按用户名搜索用户
    $query=mysql\u query(“从用户名为“%$userSearch%”的用户中选择用户名、邮政编码、用户id”);
    $rowcount=mysql\u num\u行($query);
    如果($userSearch==“”){
    }否则{
    如果($rowcount!=0){
    while($row=mysql\u fetch\u assoc($query)){
    $username=$row['username'];
    $postcode=$row['postcode'];
    $user_id=$row['user_id'];
    $sql=mysql\u query(“从用户中选择邮政编码,其中用户id=$user\u id”);
    $results=mysql\u fetch\u assoc($sql);
    echo$results['postcode'];
    $distance=getDistance($user_data['postcode',$postcode]);
    //我不确定$user_数据来自何处,但它在您的原始代码中
    回显“.$postcode.”是:'.number_格式($distance[“miles”],2)。“Mile(s)away.“
    ”;//返回结果 } }否则{ 回显“未找到用户”; } } } 函数getDistance($start,$end){ //谷歌地图API,返回两个邮政编码之间的距离 $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&sensor=false”; $data=@file\u get\u contents($url); $result=json_decode($data,true); //print_r($result);//输出数组 返回数组(//转换单位 “米”=>$result[“行”][0][“元素”][0][“距离”][“值”], “公里数”=>$result[“行”][0][“元素”][0][“距离”][“值”]/1000, “码数”=>$result[“行”][0][“元素”][0][“距离”][“值”]*1.0936133, “英里”=>$result[“行”][0][“元素”][0][“距离”][“值”]*0.000621371 ); }

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

    $data
    中有什么内容?您是否手动验证了查询url是否有效?如果我在搜索字段中键入Alex(例如)并键入var_dump($data);我得到:Alex LU6 4QP是:0.00英里以外的字符串(246)“{”目的地地址“:[”,“来源地址“:[“Luton LU2 0LG,UK”],“行“:[{”元素“:[{”状态“:“未找到”}],“状态“:“确定”}”$结果显示:Alex LU6 4QP是:0.00英里以外的数组(4){[“目的地地址”=>数组(1){[0]=>字符串(0)”[“origin_addresses”]=>array(1){[0]=>string(17)“Luton LU2 0LG,UK”}[“rows”]=>array(1){[0]=>array(1){[0]=>array(1){[0]=>string(9)“NOT_FOUND”}}[“status”=>string(2)“OK”}在测试时,是否打印($result),已注释掉,显示正确的数组?发现您的问题:)您的邮政编码1前缺少$url@max82fr见上文changes@max82fr看看我对答案的修改!你修好了!!!天才!!非常感谢!!!我如何给你一个绿色的记号来表示感谢???没问题,很高兴我能帮忙:)谢谢你的记号…我真的ly不知道你可以用google maps API实现这一点,所以也感谢你的代码:尽管我刚刚意识到,如果我在搜索框中键入一个返回多个用户的字母,所有用户的距离输出为0.00英里