Get closest locations by latitude longitude SQL math statement


/ Published in: PHP
Save to your folder(s)

Expects databaseTable to have both lat and lon columns with appropriate location coordinate data.


Copy this code and paste it in your HTML
  1. $lat = trim($_REQUEST['lat']);
  2. $lng = trim($_REQUEST['lng']);
  3.  
  4. $lat = (!empty($lat)? $lat : 41.3423502);
  5. $lng = (!empty($lng)? $lng : -73.0774616);
  6.  
  7. $HelpQuery = sprintf("SELECT *, ( 3959 * acos( cos( radians( %s ) ) * cos( radians( lat ) ) * cos( radians( lng ) - radians( %s ) ) + sin( radians( %s ) ) * sin( radians( lat ) ) ) ) AS distance FROM databaseTable ORDER BY distance LIMIT 0,5",$lat,$lng,$lat);
  8.  
  9. $HelpResult = mysql_query($HelpQuery);
  10. $result = array();
  11. $result['info'] = "";
  12.  
  13. if($HelpResult)
  14. {
  15. while($Helprow = mysql_fetch_assoc($HelpResult))
  16. {
  17. $Helprow['distance'] = round($Helprow['distance'],2);
  18. $result['info'][] = $Helprow;
  19. }
  20. }
  21. else
  22. {
  23. $result['info'] = "Error";
  24. }

Report this snippet


Comments

RSS Icon Subscribe to comments

You need to login to post a comment.