2015-03-12 4 views
26

Я пытаюсь получить вождения расстояние между двумя точками с помощью API Карт Google. Теперь у меня есть код, который получит прямое расстояние:Получите расстояние между двумя точками, используя API Карт Google

Эта функция получить широты и LNG:

function get_coordinates($city, $street, $province) 
{ 
    $address = urlencode($city.','.$street.','.$province); 
    $url = "http://maps.google.com/maps/api/geocode/json?address=$address&sensor=false&region=Poland"; 
    $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); 
    $return = array('lat' => $response_a->results[0]->geometry->location->lat, 'long' => $long = $response_a->results[0]->geometry->location->lng); 

    return $return; 
} 

Эта функция высчитывает расстояние между двумя точками на основе лат & LNG:

function getDistanceBetweenPoints($lat1, $lon1, $lat2, $lon2) { 
    $theta = $lon1 - $lon2; 
    $miles = (sin(deg2rad($lat1)) * sin(deg2rad($lat2))) + (cos(deg2rad($lat1)) * cos(deg2rad($lat2)) * cos(deg2rad($theta))); 
    $miles = acos($miles); 
    $miles = rad2deg($miles); 
    $miles = $miles * 60 * 1.1515; 
    $kilometers = $miles * 1.609344; 
    return $kilometers; 
} 

Эта функция расстояние печати на километры:

function get_distance($lat1, $lat2, $long1, $long2) 
{ 
    /* These are two points in New York City */ 
    $point1 = array('lat' => $lat1, 'long' => $long1); 
    $point2 = array('lat' => $lat2, 'long' => $long2); 

    $distance = getDistanceBetweenPoints($point1['lat'], $point1['long'], $point2['lat'], $point2['long']); 
    return $distance; 
} 

Использование:

$coordinates1 = get_coordinates('Katowice', 'Korfantego', 'Katowicki'); 
$coordinates2 = get_coordinates('Tychy', 'Jana Pawła II', 'Tyski'); 

echo 'Distance: <b>'.round(get_distance($coordinates1['lat'], $coordinates2['lat'], $coordinates1['long'], $coordinates2['long']), 1).'</b> km'; 

Но этот код получить прямое расстояние. Мне нужно проехать. Как я могу проехать с помощью API Google Maps?

Благодарим за помощь!

+0

Вы пробовали посмотреть на [матрицу расстояний] (https://developers.google.com/maps/documentation/distancematrix/#DistanceMatrixRequests) API? –

+0

@VivekPradhan ye. Это было полезно: https://maps.googleapis.com/maps/api/distancematrix/json?origins=50.1112251,18.9903966&destinations=50.1369031,19.1012599&mode=driving&language=pl-PL Спасибо! – Newester

ответ

44

ОК, я нашел решение, используя матрицу расстояний: https://developers.google.com/maps/documentation/distancematrix/#DistanceMatrixRequests

Эта функция получить широчайшие & LNG от города, адрес, провинция:

function get_coordinates($city, $street, $province) 
{ 
    $address = urlencode($city.','.$street.','.$province); 
    $url = "http://maps.google.com/maps/api/geocode/json?address=$address&sensor=false&region=Poland"; 
    $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); 
    $status = $response_a->status; 

    if ($status == 'ZERO_RESULTS') 
    { 
     return FALSE; 
    } 
    else 
    { 
     $return = array('lat' => $response_a->results[0]->geometry->location->lat, 'long' => $long = $response_a->results[0]->geometry->location->lng); 
     return $return; 
    } 
} 

Эта функция высчитывает вождения расстояние и время в пути продолжительность:

function GetDrivingDistance($lat1, $lat2, $long1, $long2) 
{ 
    $url = "https://maps.googleapis.com/maps/api/distancematrix/json?origins=".$lat1.",".$long1."&destinations=".$lat2.",".$long2."&mode=driving&language=pl-PL"; 
    $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); 
    $dist = $response_a['rows'][0]['elements'][0]['distance']['text']; 
    $time = $response_a['rows'][0]['elements'][0]['duration']['text']; 

    return array('distance' => $dist, 'time' => $time); 
} 

Использование:

Возврат:

Расстояние: 11,2 км Travel длительность: 15 мин

+0

Keep Coding .. :) –

+0

wat does 11,2km определяет здесь? – Learner

+0

@ humbledust просто измените язык по URL-адресу – Hvn

13

Вы можете сделать это с помощью Google Distance Matrix API:

// $details = "http://maps.googleapis.com/maps/api/distancematrix/json?origins=Seattle&destinations=San+Francisco&mode=driving&sensor=false"; 

    //you can also pass latitude/longitude values in origins 


    $details = "http://maps.googleapis.com/maps/api/distancematrix/json?origins=41.43206,-81.38992&destinations=San+Francisco&mode=driving&sensor=false"; 


    $json = file_get_contents($details); 

    $details = json_decode($json, TRUE); 

    echo "<pre>"; print_r($details); echo "</pre>"; 

Вот ссылка на API-интерфейс для определения расстояния в Google: - https://developers.google.com/maps/documentation/distancematrix/?csw=1

1

API-интерфейс матрицы расстояний выполнит работу, тогда нет необходимости вычислять координаты с помощью адреса и d, тогда расстояние !!

Вот АНИ
https://maps.googleapis.com/maps/api/distancematrix/json?origins=orginaddress&destinations=destinationaddress&key=YOUR_API_KEY

PHP код:

$ch = "https://maps.googleapis.com/maps/api/distancematrix/json?origins=orginaddress&destinations=destinationaddress&key=YOUR_API_KEY"; 
$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); 
//print_($response_a); 
1

Это метод, который я получил. В нем вы можете ввести любое ручное расстояние от сеансов или базы данных.

$origin = urlencode($_SESSION['source1']); 
$destination = urlencode($_SESSION['dest1']); 

$url = "https://maps.googleapis.com/maps/api/distancematrix/json?origins=$origin&destinations=$destination&key=Your api key; 

$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); 
?> 

Теперь сложной частью было показать расстояние.Хорошо, с исследованиями, я получил этот ответ:

<div class=""> 
    <?php echo $response_a['rows'][0]['elements'][0]['distance']['text']; ?> 

</div> 

Вы можете распечатать этот результат в любом месте. Это работает для меня.

Смежные вопросы