PHP calculates distance between cities

2

With the code below I can calculate the distance from one city to another, but I can only put cep's would have some way of using the proper names of the cities instead of the zip codes?

$i = 0;
$arr = array('90450000','95180000');

foreach ($arr as &$valuedestino) {


    $origin = '95700000';
    $destino = $valuedestino;



    $url = "http://maps.googleapis.com/maps/api/distancematrix/json?origins=$origin&destinations=$destino&mode=driving&language=en-EN&sensor=false";

    $data = @file_get_contents($url);

    $result = json_decode($data, true);

    foreach($result['rows'] as $distance) {
        $i++;
        echo '<br>';
        echo "$i - Distance from you: " . $distance['elements'][0]['distance']['text'] . ' (' . $distance['elements'][0]['duration']['text'] . ' in current traffic)';
    }
}
    
asked by anonymous 15.09.2016 / 20:33

1 answer

2

Replace ZIP codes with city names in the parameters $origem and $destino and use str_replace to replace spaces with %20 . Look:

<?php

$i = 0;
$arr = array('rio de janeiro','belo horizonte');

foreach ($arr as &$valuedestino) {

    $origin = 'sao paulo';
    $destino = $valuedestino;

    $origin = str_replace(' ', '%20', $origin);
    $destino = str_replace(' ', '%20', $destino);

    $url = "http://maps.googleapis.com/maps/api/distancematrix/json?origins=$origin&destinations=$destino&mode=driving&language=en-EN&sensor=false";

    $data = @file_get_contents($url);

    $result = json_decode($data, true);

    foreach($result['rows'] as $distance) {
        $i++;
        echo '<br>';
        echo "$i - Distance from you: " . $distance['elements'][0]['distance']['text'] . ' (' . $distance['elements'][0]['duration']['text'] . ' in current traffic)';
    }
}
?>
    
15.09.2016 / 20:49