Search code examples
phplatitude-longitude

How to calculate distance from lat/long in php?


What I am trying to do is I have entries in the database which have a lat/long stored with them. I want to calculate the distance between users lat/long and entries lat/long (in DB). After that, I want to echo the ones with distance less than 500 meters. So far I am able to do this using foreach.

<?php
mysql_connect("localhost", "beepbee_kunwarh", "kunwar") or die('MySQL Error.');
mysql_select_db("beepbee_demotest") or die('MySQL Error.');

$Lat = $_REQUEST['Lat'];
$long = $_REQUEST['long'];

$query = mysql_query("SELECT a.*, 3956 * 2 * ASIN(SQRT( POWER(SIN(($Lat - Lat) * pi()/180 / 2), 2) + COS($Lat * pi()/180) * COS(Lat * pi()/180) *POWER(SIN(($long - long) * pi()/180 / 2), 2) )) as distance FROM userResponse GROUP BY beepid HAVING distance <= 500 ORDER by distance ASC;");
$data = array();
while ($row = mysql_fetch_array($query)) {
    $data[] = $row;
}
echo json_encode($data);
?>

Solution

  • I did this a few weeks ago.

    This link is your best bet:

    http://code.google.com/apis/maps/articles/phpsqlsearch.html

    Even if you don't use their API, their PHP and SQL query helped really well.