PHP performs nearby location query based on a given longitude and latitude point

WBOY
Release: 2016-07-25 08:45:48
Original
1279 people have browsed it
The implementation principle is to first calculate the four points of the rectangle around the point, and then use the longitude and latitude to directly match the records in the database.
  1. //Get surrounding coordinates
  2. public function returnSquarePoint($lng, $lat,$distance = 0.5){
  3. $earthRadius = 6378138;
  4. $dlng = 2 * asin(sin($distance / (2 * $earthRadius )) / cos(deg2rad($lat)));
  5. $dlng = rad2deg($dlng);
  6. $dlat = $distance/$earthRadius;
  7. $dlat = rad2deg($dlat);
  8. return array(
  9. 'left -top'=>array('lat'=>$lat + $dlat,'lng'=>$lng-$dlng),
  10. 'right-top'=>array('lat'=> $lat + $dlat, 'lng'=>$lng + $dlng),
  11. 'left-bottom'=>array('lat'=>$lat - $dlat, 'lng'=>$lng - $dlng),
  12. 'right-bottom'=>array('lat'=>$lat - $dlat, 'lng'=>$lng + $dlng)
  13. );
  14. }
  15. //Calculate two The straight-line distance of coordinates
  16. public function getDistance($lat1, $lng1, $lat2, $lng2){
  17. $earthRadius = 6378138; // Approximate earth radius in meters
  18. // Convert to radians
  19. $lat1 = ($lat1 * pi()) / 180;
  20. $lng1 = ($lng1 * pi()) / 180;
  21. $lat2 = ($lat2 * pi()) / 180;
  22. $lng2 = ($lng2 * pi()) / 180;
  23. // Use the semisine formula to calculate with a ruler and compass
  24. $calcLongitude = $lng2 - $lng1;
  25. $calcLatitude = $lat2 - $lat1;
  26. $stepOne = pow(sin($calcLatitude / 2), 2 ) + cos($lat1) * cos($lat2) * pow(sin($calcLongitude / 2), 2);
  27. $stepTwo = 2 * asin(min(1, sqrt($stepOne)));
  28. $calculatedDistance = $earthRadius * $stepTwo;
  29. return round($calculatedDistance);
  30. }
Copy code

PHP


source:php.cn
Statement of this Website
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn
Popular Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template