我有一個類我專門用於此:
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']
];
}
}
無論是將太多可能的答案,還是很好的答案就太長了這種格式。請添加詳細信息以縮小答案集或隔離可以在幾個段落中回答的問題。我建議您找到一個開發論壇(可能是[Quora](http://www.quora.com/Computer-Programming) ?)來計算一般性。然後,當/如果您有特定的編碼問題,請回到StackOverflow,我們很樂意提供幫助。 –
作爲一個提示,不要使用Pythagorus定理,除非距離非常近 - 你更可能需要大圓距離 –
另外,值得一看[OS的OpenData](https://www.ordnancesurvey.co。 uk/opendatadownload/products.html)([My Society mirror](http://parlvid.mysociety.org/os/)) –