PHP performs nearby location query based on a given longitude and latitude point
Release: 2016-07-25 08:45:48
Original
1229 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.
- //Get surrounding coordinates
- public function returnSquarePoint($lng, $lat,$distance = 0.5){
- $earthRadius = 6378138;
- $dlng = 2 * asin(sin($distance / (2 * $earthRadius )) / cos(deg2rad($lat)));
- $dlng = rad2deg($dlng);
- $dlat = $distance/$earthRadius;
- $dlat = rad2deg($dlat);
- return array(
- 'left -top'=>array('lat'=>$lat + $dlat,'lng'=>$lng-$dlng),
- 'right-top'=>array('lat'=> $lat + $dlat, 'lng'=>$lng + $dlng),
- 'left-bottom'=>array('lat'=>$lat - $dlat, 'lng'=>$lng - $dlng),
- 'right-bottom'=>array('lat'=>$lat - $dlat, 'lng'=>$lng + $dlng)
- );
- }
- //Calculate two The straight-line distance of coordinates
- public function getDistance($lat1, $lng1, $lat2, $lng2){
- $earthRadius = 6378138; // Approximate earth radius in meters
- // Convert to radians
- $lat1 = ($lat1 * pi()) / 180;
- $lng1 = ($lng1 * pi()) / 180;
- $lat2 = ($lat2 * pi()) / 180;
- $lng2 = ($lng2 * pi()) / 180;
- // Use the semisine formula to calculate with a ruler and compass
- $calcLongitude = $lng2 - $lng1;
- $calcLatitude = $lat2 - $lat1;
- $stepOne = pow(sin($calcLatitude / 2), 2 ) + cos($lat1) * cos($lat2) * pow(sin($calcLongitude / 2), 2);
- $stepTwo = 2 * asin(min(1, sqrt($stepOne)));
- $calculatedDistance = $earthRadius * $stepTwo;
- return round($calculatedDistance);
- }
Copy code
|
PHP
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
Latest Articles by Author
-
2024-08-25 12:40:24
-
2024-08-25 12:35:24
-
2024-08-25 12:31:38
-
2024-08-25 12:30:55
-
2024-08-25 12:26:24
-
2024-08-25 12:21:24
-
2024-08-25 12:16:24
-
2024-08-25 12:15:24
-
2024-08-25 12:13:24
-
2024-08-25 12:11:24