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
|