How to calculate distance from lat/long in php?

后端 未结 9 1364
余生分开走
余生分开走 2020-12-09 06:18

What I am trying to do is I have entries in the database which have a lat/long stored with them. I want to calculate the distance between users lat/long and entries lat/long

相关标签:
9条回答
  • 2020-12-09 06:24

    I did this a few weeks ago.

    This link is your best bet:

    http://code.google.com/apis/maps/articles/phpsqlsearch.html

    Even if you don't use their API, their PHP and SQL query helped really well.

    0 讨论(0)
  • 2020-12-09 06:27

    Tested like 3 functions and 3 queries and only one showed good distance:

    In meters:

    SELECT *,
    (
        (((acos(sin((".$latitude."*pi()/180)) * sin((`latitude`*pi()/180))+cos((".$latitude."*pi()/180))    * cos((`latitude`*pi()/180)) * cos(((".$longitude."- `longitude`)*pi()/180))))*180/pi())*60*1.1515*1.609344) 
        * 1000
    ) as `distance`
    FROM `table`
    ORDER BY `distance` ASC
    

    In kilometers:

    SELECT *,
    (
        (((acos(sin((".$latitude."*pi()/180)) * sin((`latitude`*pi()/180))+cos((".$latitude."*pi()/180))    * cos((`latitude`*pi()/180)) * cos(((".$longitude."- `longitude`)*pi()/180))))*180/pi())*60*1.1515*1.609344) 
    ) as `distance`
    FROM `table`
    ORDER BY `distance` ASC
    
    0 讨论(0)
  • 2020-12-09 06:27

    For those trying to stay away from Google (and others) APIs, I've been using this one for a while.

    Because the earth is round, it will have some weird results for large scale radius submissions. It will work fine for locations within ~500 miles of each other.

    /**
     * The max Latitude and Longitude coordinates within a specified milage radius.
     * 
     * @param int $miles
     * @param float $longitude
     * @param float $latitude
     *
     * @return array
     */
    public function getMaxCoordinates($miles = 50, $longitude, $latitude) {
        $oneDegree = 69; // 69 Miles = 1 degree
    
        // Calculate the minimum/maximum possible coordinates.
        $lng_min = $longitude - $miles / abs(cos(deg2rad($latitude)) * $oneDegree);
        $lng_max = $longitude + $miles / abs(cos(deg2rad($latitude)) * $oneDegree);
        $lat_min = $latitude  - ($miles / $oneDegree);
        $lat_max = $latitude  + ($miles / $oneDegree);
    
        return ([
            'lat_max' => $lat_max,
            'lat_min' => $lat_min,
            'lng_max' => $lng_max,
            'lng_min' => $lng_min,
            'miles'   => $miles,
        ]);
    }
    
    0 讨论(0)
  • 2020-12-09 06:30

    This query was perfect for me:

    $latitude = "23.139422";  //your current lat
    $longitude = "-82.382617"; //your current long
    
    SELECT ( 3959 * acos( cos( radians( '.$latitude.' ) ) * cos( radians( latitude ) ) * 
     cos( radians( longitude ) - radians( '.$longitude.' ) ) + sin( radians( '.$latitude.' )
     ) * sin( radians( latitude ) ) ) ) AS distance from TABLE 
     HAVING distance <= 100 ORDER BY distance ASC
    
    0 讨论(0)
  • 2020-12-09 06:31

    i would not recommend dumping distance calculations in your sql statement, even though i admit that the solution presented by 'denil' is ingenious.

    there are 3 downsides: code maintenance, sql server overload AND (above all) the earth is not symmetrical (it is like an old dented baseball that was run over by a truck). this means that you might want to change the code in the future (there are some VERY sophisticated algorithms out there - http://en.wikipedia.org/wiki/Geographical_distance).

    i recommend using a separate function that calculates distance with a simple common algorithm (similar if not identical to denil's). i submit this code which is pure php (no need to use googlemaps api):

    <?php
    
    function distanceGeoPoints ($lat1, $lng1, $lat2, $lng2) {
    
        $earthRadius = 3958.75;
    
        $dLat = deg2rad($lat2-$lat1);
        $dLng = deg2rad($lng2-$lng1);
    
    
        $a = sin($dLat/2) * sin($dLat/2) +
           cos(deg2rad($lat1)) * cos(deg2rad($lat2)) *
           sin($dLng/2) * sin($dLng/2);
        $c = 2 * atan2(sqrt($a), sqrt(1-$a));
        $dist = $earthRadius * $c;
    
        // from miles
        $meterConversion = 1609;
        $geopointDistance = $dist * $meterConversion;
    
        return $geopointDistance;
    }
    
    // YOUR CODE HERE
    echo distanceGeoPoints(22,50,22.1,50.1);
    
    ?>
    

    there are a number of free softwares (try gps trackmaker) that will allow you to check the margin of error for your part of the globe (if you need precision). for the above lat/long pair, the error is within +/- 0.1% (according to local topographers).

    ATTENTION: this formula gives you CARTOGRAPHIC distance (distance at sea level), not TOPOGRAPHIC distance (disconsiders topography).

    0 讨论(0)
  • 2020-12-09 06:37

    Try this query. I found this one when googling but forgot who created it

    SELECT a.*,
                3956 * 2 * ASIN(SQRT( POWER(SIN(($lat - lat) * pi()/180 / 2), 2) + COS($lat * pi()/180) * COS(lat * pi()/180) *
                POWER(SIN(($long - longi) * pi()/180 / 2), 2) )) as
                distance FROM table
                GROUP BY id HAVING distance <= 500 ORDER by distance ASC
    

    $lat and $long variable is the current position of user. lat and longi is the latitude and longitudle of entries

    0 讨论(0)
提交回复
热议问题