PHP查询附近的人及其距离的实现方法
本文实例讲述了PHP查询附近的人及其距离的实现方法。
1 <?php 2 //获取该点周围的4个点 3 $distance = 1;//范围(单位千米) 4 $lat = 113.873643; 5 $lng = 22.573969; 6 define('EARTH_RADIUS', 6371);//地球半径,平均半径为6371km 7 $dlng = 2 * asin(sin($distance / (2 * EARTH_RADIUS)) / cos(deg2rad($lat))); 8 $dlng = rad2deg($dlng); 9 $dlat = $distance / EARTH_RADIUS; 10 $dlat = rad2deg($dlat); 11 $squares = array('left-top' => array('lat' => $lat + $dlat, 'lng' => $lng - $dlng), 12 'right-top' => array('lat' => $lat + $dlat, 'lng' => $lng + $dlng), 13 'left-bottom' => array('lat' => $lat - $dlat, 'lng' => $lng - $dlng), 14 'right-bottom' => array('lat' => $lat - $dlat, 'lng' => $lng + $dlng) 15 ); 16 print_r($squares['left-top']['lat']); 17 //从数库查询匹配的记录 18 $info_sql = "select * from `A` where lat<>0 and lat>{$squares['right-bottom']['lat']} and lat<{$squares['left-top']['lat']} and lng>{$squares['left-top']['lng']} and lng<{$squares['right-bottom']['lng']} "; 19 //获取两点之间的距离 20 function getDistanceBetweenPointsNew($latitude1, $longitude1, $latitude2, $longitude2) 21 { 22 $theta = $longitude1 - $longitude2; 23 $miles = (sin(deg2rad($latitude1)) * sin(deg2rad($latitude2))) + (cos(deg2rad($latitude1)) * cos(deg2rad($latitude2)) * cos(deg2rad($theta))); 24 $miles = acos($miles); 25 $miles = rad2deg($miles); 26 $miles = $miles * 60 * 1.1515; 27 $feet = $miles * 5280; 28 $yards = $feet / 3; 29 $kilometers = $miles * 1.609344; 30 $meters = $kilometers * 1000; 31 return compact('miles', 'feet', 'yards', 'kilometers', 'meters'); 32 } 33 34 $point1 = array('lat' => 40.770623, 'long' => -73.964367); 35 $point2 = array('lat' => 40.758224, 'long' => -73.917404); 36 $distance = getDistanceBetweenPointsNew($point1['lat'], $point1['long'], $point2['lat'], $point2['long']); 37 foreach ($distance as $unit => $value) { 38 echo $unit . ': ' . number_format($value, 4) . '<br />'; 39 } 40 ?>