我想显示酒店和用户之间的距离。 计算酒店和用户地址之间的距离我已经使用了以下代码。距离值我点击了按钮。如何使用php计算两地之间的距离?
1)首先我得到使用IP地址并从IP地址获取所有用户地址信息。
$ipAddress = $_SERVER['REMOTE_ADDR'];
$result = json_decode(file_get_contents("http://ip-api.com/json/{$ipAddress}"));
这个电话给我详细的城市,国家,countryCode,纬度,经度,邮编等。保存经纬度。 2)我在我们的数据库中已经有酒店经纬度。
now I have four value. User latitude/longitude and Hotel latitude/longitude
$lat1 = $user_latitude;
$long1 = $user_longitude;
$lat2 = $hotel_latitude;
$long2 = $hotel_longitude;
3)之后,在使用谷歌地图API的我已经得到双方的完整地址(用户和酒店)
$url = "http://maps.googleapis.com/maps/api/geocode/json?latlng={$lat1},{$long1}&sensor=true";
$url2 = "http://maps.googleapis.com/maps/api/geocode/json?latlng={$lat2},{$long2}&sensor=true";
# Get address of User
$ch = curl_init();
curl_setopt($ch, CURLOPT_URL, $url);
curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1);
curl_setopt($ch, CURLOPT_PROXYPORT, 3128);
curl_setopt($ch, CURLOPT_SSL_VERIFYHOST, 0);
curl_setopt($ch, CURLOPT_SSL_VERIFYPEER, 0);
$response = curl_exec($ch);
curl_close($ch);
$response_a = json_decode($response, true);
$address1 = $response_a['results'][0]['formatted_address'];
# Get address of Hotel
$ch = curl_init();
curl_setopt($ch, CURLOPT_URL, $url2);
curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1);
curl_setopt($ch, CURLOPT_PROXYPORT, 3128);
curl_setopt($ch, CURLOPT_SSL_VERIFYHOST, 0);
curl_setopt($ch, CURLOPT_SSL_VERIFYPEER, 0);
$response = curl_exec($ch);
curl_close($ch);
$response_a = json_decode($response, true);
$address2 = $response_a['results'][0]['formatted_address'];
$find = array("'",'"');
$replace = array("","");
$address1 = str_replace($find,$replace,$address1);
$address2 = str_replace($find,$replace,$address2);
4)最后,我有谷歌的使用距离矩阵API和获得两点之间的距离。
$url = "https://maps.googleapis.com/maps/api/distancematrix/json?origins=".$lat1.",".$long1."&destinations=".$lat2.",".$long2."&alternatives=true&mode=driving&language=de-DE&sensor=false";
$ch = curl_init();
curl_setopt($ch, CURLOPT_URL, $url);
curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1);
curl_setopt($ch, CURLOPT_PROXYPORT, 3128);
curl_setopt($ch, CURLOPT_SSL_VERIFYHOST, 0);
curl_setopt($ch, CURLOPT_SSL_VERIFYPEER, 0);
$response = curl_exec($ch);
curl_close($ch);
$response_a = json_decode($response, true);
$distance = $response_a['rows'][0]['elements'][0]['distance']['text'];
$time = $response_a['rows'][0]['elements'][0]['duration']['text'];
5)距离保存在$distance
和总时间节省$时间。它还提供了您在$response_a
中查看的其他详细信息。打印$response_a
的值。
但所有的时间它给我不正确的距离。
一旦你有两个纬度/经度,你只需使用*大圆距离公式*;这很简单,查看它。无需将坐标转换为地址并使用API。说完这句话,是的,在IP *上查找一个位置*只会给你非常非常好的***粗糙的位置,准确性只能达到城市或州级别;在几公里内绝对不准确。 – deceze