计算距离PHP并添加到JSON

时间:2013-11-22 19:00:53

标签: php mysql json gps distance

我正在尝试将计算的距离添加到我的JSON中。我有以下代码,但它没有正确返回距离。我通过URL参数从我的应用程序传递经度和纬度并浸泡到变量中,我在mySQL中存储了经度和纬度,我希望将其与从URL传递到计算距离的内容进行比较。

function getDistanceBetweenPointsNew($latitude1, $longitude1, $latitude2, $longitude2) {    
$theta = $longitude1 - $longitude2;
$miles = (sin(deg2rad($latitude1)) * sin(deg2rad($latitude2))) + (cos(deg2rad($latitude1)) * cos (deg2rad($latitude2)) * cos(deg2rad($theta)));
$miles = acos($miles);
$miles = rad2deg($miles);
$miles = $miles * 60 * 1.1515;
$kilometers = $miles * 1.609344;
return compact('miles','kilometers'); 
}

/* require the user as the parameter */
if(isset($_GET['user']) && intval($_GET['user'])) {

/* soak in the passed variable or set our own */
$latitude2 = floatval($_GET['latitude']); //no default
$longitude2 = floatval($_GET['longitude']); //no default

/* connect to the db */
$link = mysql_connect('mydatabase.com','user','pass') or die('Cannot connect to the DB');
mysql_select_db('mydatabase',$link) or die('Cannot select the DB');

/* grab the posts from the db */
 $query = "SELECT * FROM items,category WHERE items.category_id = category.key;
 //$query = "SELECT * FROM items, category";
 $result = mysql_query($query,$link) or die('Errant query:  '.$query);
 while($row = mysql_fetch_array($result))
{

$point1 = array('lat' => number_format ($latitude,4,'.',''), 'long' => number_format ($longitude,4,'.',''));
$point2 = array('lat' => number_format ($latitude2,4,'.',''), 'long' => number_format ($longitude2,4,'.',''));
$distance = getDistanceBetweenPointsNew($point1['lat'], $point1['long'], $point2['lat'], $point2['long']);

extract($row);
$channel['items'][$category_name][] = array(
    'title' => $title,
'category_id' => $category_id,
'distance' => $distance,
'latitude1' => $latitude,
'longitude1' => $longitude,
'category_name' => $category_name,
'category_key' => $key,
);
}   
$channels = array($channel);
$json = json_encode($channel);
header('Content-type: application/json');
echo $json;
}

这给了我这个JSON作为例子。在这种情况下,disance应为0(零),因为我已将URL参数设置为与数据库中的相同。

{
"items": {
    "category_name": [
        {
            "title": "trying with category id again",
            "category_id": "3",
            "distance": {
                "miles": 7821.7038119937,
                "kilometers": 12587.812099609
            },
            "latitude1": "-119.5430000",
            "longitude1": "30.4310000",
            "category_name": "category_name",
            "category_key": "3"
        },
        {

我确信这不是最干净的代码,但是我很新,这是我到目前为止所提出的。任何帮助将不胜感激!

2 个答案:

答案 0 :(得分:1)

简单......

extract($row);移到$point1 = ...

之上

答案 1 :(得分:0)

以下SQL查询使用Spherical Law of Cosines来计算表中坐标和坐标之间的距离。

  

d = acos(sin(f1).sin(f2)+ cos(f1).cos(f2).cos(??))。R

查询使用SQL Math functions

require("dbinfo.php");//database parameters
// Get parameters from URL
$center_lat = $_GET["lat"];
$center_lng = $_GET["lng"];
$radius =  $_GET["radius"];

$arr = array();
//Connect to database
$dbh = new PDO("mysql:host=$host;dbname=$database", $username, $password);
$dbh->setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION);
try {
    // Prepare statement
    $stmt = $dbh->prepare("SELECT  name, lat, lng, ( 3959 * acos( cos( radians(?) ) * cos( radians( lat ) ) * cos( radians( lng ) - radians(?) ) + sin( radians(?) ) * sin( radians( lat ) ) ) ) AS distance FROM gbstn HAVING distance < ? ORDER BY distance LIMIT 0 , 20");
    // Assign parameters
    $stmt->bindParam(1,$center_lat);
    $stmt->bindParam(2,$center_lng);
    $stmt->bindParam(3,$center_lat);
    $stmt->bindParam(4,$radius);
    //Execute query
    $stmt->setFetchMode(PDO::FETCH_OBJ);
    $stmt->execute();
    //Show the results  
    while($obj = $stmt->fetch()) {  
        $arr[] = $obj;
    }
    if (count($arr) >= 1)
    {
        echo '{"marker":'.json_encode($arr).'}';
    }else{
        echo '{"marker":[{"name":"No Results","lat":'.$center_lat.',"lng":'.$center_lng.',"distance":0}]}';  
    }

}


catch(PDOException $e) {
    echo "I'm sorry I'm afraid you can't do that.". $e->getMessage() ;// Remove or modify after testing 
    file_put_contents('PDOErrors.txt',date('[Y-m-d H:i:s]').", mapSelect.php, ". $e->getMessage()."\r\n", FILE_APPEND);  
 }
//Close the connection
$dbh = null; 
?>

使用PDO代替弃用的mysql_函数。

您需要修改适合的声明。调试后也删除catch块中的echo。