问题
I have looked at other questions that have been answered however, I am still unsure on how to;
Get UK postcode data including Longitude, Latitude, Grid-N and Grid-E into my database
If I use an API how do I go about it? Where do I start from?
- Would I need to use Pythagorus Theorem to calculate the distance between the two postcodes?
- 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}®ion=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