Welcome to ShenZhenJia Knowledge Sharing Community for programmer and developer-Open, Learning and Share
menu search
person
Welcome To Ask or Share your Answers For Others

Categories

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

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
thumb_up_alt 0 like thumb_down_alt 0 dislike
172 views
Welcome To Ask or Share your Answers For Others

1 Answer

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']
        ];
    }
}

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
thumb_up_alt 0 like thumb_down_alt 0 dislike
Welcome to ShenZhenJia Knowledge Sharing Community for programmer and developer-Open, Learning and Share
...