PHP calculates distance between cities

Asked

Viewed 1,697 times

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 to use the city’s own names instead of cep’s ?

$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)';
    }
}

1 answer

2


Replace Zip Codes with city names in parameters $origem and $destino and use the str_replace to replace spaces by %20. Behold:

<?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)';
    }
}
?>

Browser other questions tagged

You are not signed in. Login or sign up in order to post.