PHP queries nearby locations based on a given latitude and longitude point

Source: Internet
Author: User
Tags asin
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.

  1. // Obtain the surrounding coordinates
  2. Public function returnSquarePoint ($ lng, $ lat, $ distance = 0.5 ){
  3. $ EarthRadius = 6378138;
  4. $ Dlng = 2 * asin (sin ($ distance/(2 * $ earthRadius)/cos (deg 2rad ($ 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 the linear distance between two coordinates
  16. Public function getDistance ($ lat1, $ lng1, $ lat2, $ lng2 ){
  17. $ EarthRadius = 6378138; // approximate Earth radius meter
  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 semi-positive vector formula to calculate the size
  24. $ Calclong133 = $ 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. }


PHP

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.