PHP queries nearby locations based on a given latitude and longitude point
The implementation principle first calculates the four points of the rectangle around the point, and then uses the longitude and latitude to directly match the records in the database.
- // Obtain the surrounding coordinates
- Public function returnSquarePoint ($ lng, $ lat, $ distance = 0.5 ){
- $ EarthRadius = 6378138;
- $ Dlng = 2 * asin (sin ($ distance/(2 * $ earthRadius)/cos (deg 2rad ($ 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 the linear distance between two coordinates
-
- Public function getDistance ($ lat1, $ lng1, $ lat2, $ lng2 ){
- $ EarthRadius = 6378138; // approximate Earth radius meter
- // Convert to radians
- $ Lat1 = ($ lat1 * pi ()/180;
- $ Lng1 = ($ lng1 * pi ()/180;
- $ Lat2 = ($ lat2 * pi ()/180;
- $ Lng2 = ($ lng2 * pi ()/180;
- // Use the semi-positive vector formula to calculate the size
- $ Calclong133 = $ 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 );
- }
|
PHP