How to calculate distance from lat/long in php?

后端 未结 9 1401
余生分开走
余生分开走 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: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,
        ]);
    }
    

提交回复
热议问题