Working out the distance between two postcodes

拟墨画扇 提交于 2020-01-07 09:07:11

问题


I have looked at other questions that have been answered however, I am still unsure on how to;

  1. Get UK postcode data including Longitude, Latitude, Grid-N and Grid-E into my database

  2. If I use an API how do I go about it? Where do I start from?

  3. Would I need to use Pythagorus Theorem to calculate the distance between the two postcodes?
  4. I have got a table in my database for when a user adds a property. Maybe, there is a way when someone adds a property, it can add that postcode along with the postcodes other information (long, lat, grid-ref) into my Postcodes table so that I can work out the distance between the two postcodes.

Thanks


回答1:


I have a class I use specifically for this:

class Geocode
{
    /**
     * Work out the distance between two sets of lat/lng coordinates as the crow flies.
     *
     * @param float $lat1
     * @param float $lng1
     * @param float $lat2
     * @param float $lng2
     *
     * @return float
     */
    public static function distance($lat1 = 0.0, $lng1 = 0.0, $lat2 = 0.0, $lng2 = 0.0) {
        $theta = $lng1 - $lng2;
        $dist = sin(deg2rad($lat1)) * sin(deg2rad($lat2)) +  cos(deg2rad($lat1)) * cos(deg2rad($lat2)) * cos(deg2rad($theta));
        $dist = acos($dist);
        $dist = rad2deg($dist);
        return $dist * 60 * 1.1515;
    }

    /**
     * Get the lat/lng coordinates for an address.
     *
     * @param string $address
     *
     * @return stdClass
     */
    public static function convert($address = '')
    {
        $address = str_replace(" ", "+", urlencode(str_replace(PHP_EOL, ', ', $address)));
        $url = "https://maps.googleapis.com/maps/api/geocode/json?address={$address}&region=uk&sensor=false";

        $ch = curl_init();
        curl_setopt($ch, CURLOPT_URL, $url);
        curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1);
        $response = json_decode(curl_exec($ch), TRUE);

        if($response['status'] != 'OK') {
            return (object) ['status' => $response['status']];
        }
        $geo = $response['results'][0]['geometry'];

        return (object) [
            'lat'       => $geo['location']['lat'],
            'lng'       => $geo['location']['lng'],
            'status'    => $response['status']
        ];
    }
}


来源:https://stackoverflow.com/questions/36205761/working-out-the-distance-between-two-postcodes

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!