更新时间:2022-10-18 10:28:53
我为此专门使用了一个类:
class Geocode
{
/ **
*计算两组纬度/经度坐标之间的距离。
*
* @param float $ lat1
* @param float $ lng1
* @param float $ lat2
* @param float $ lng2
*
* @return float
* /
公共静态函数距离($ 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;
}
/ **
*获取地址的纬度/经度坐标。
*
* @param字符串$地址
*
* @return stdClass
* /
公共静态函数转换($ 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'=> $响应[状态]];
}
$ geo = $ response ['results'] [0] ['geometry'];
return(object)[
'lat'=> $ geo ['location'] ['lat'],
'lng'=> $ geo ['location'] ['lng'],
'status'=> $ response ['status']
];
}
}
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?
Thanks
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']
];
}
}