I want to display distance between hotel and user. For calculation Distance between hotel and user address I have used following code. Distance value I have get on button click.
1) First I have getting use IP address and get all user address information from IP address.
$ipAddress = $_SERVER['REMOTE_ADDR'];
$result = json_decode(file_get_contents("http://ip-api.com/json/{$ipAddress}"));
This call give me details like city, country, countryCode, latitude, longitude, zip etc. Save latitude and longitude.
$user_latitude = $result->lat;
$user_longitude = $result->lon;
2) I have hotel latitude and longitude in our database already.
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) After that with the use of google map API I have get full address of both (User and Hotel)
$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) At last I have use distance matrix API of google and get distance between two points.
$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 is save in $distance
and total time save in $time. It also give other details which you view in $response_a
. Print the value of $response_a
.
But all time it give me incorrect distance.