Error 400 Bad Request in the Google Distance Calculation API

0

This is the error that is occurring at the time of sending the requisitions through the url:

Warning: file_get_contents(https://maps.googleapis.com/maps/api/distancematrix/json?origins=Av Padres Olivetanos|Brasil&destinations=AmadorBuenoDaVeiga|Brasil&mode=car&language=pt-BR): failed to open stream: HTTP request failed! HTTP/1.0 400 Bad Request in C:\xampp\htdocs\teste_xml\index.php on line 9

Warning: file_get_contents(https://maps.googleapis.com/maps/api/distancematrix/json?origins=Rua Francisco Amaral|Brasil&destinations=AmadorBuenoDaVeiga|Brasil&mode=car&language=pt-BR): failed to open stream: HTTP request failed! HTTP/1.0 400 Bad Request in C:\xampp\htdocs\teste_xml\index.php on line 9

Warning: Invalid argument supplied for foreach() in C:\xampp\htdocs\teste_xml\index.php on line 17

The error happens only when looping requests

This is the code

$dados = array('Av Padres Olivetanos', 'Rua Francisco Amaral', '');


foreach ($dados as $rua) {
    //Faz a requisicao do arquivo xml   
    $url = file_get_contents("https://maps.googleapis.com/maps/api/distancematrix/json?origins=".$rua."|Brasil&destinations=AmadorBuenoDaVeiga|Brasil&mode=car&language=pt-BR");
    $jsonObj = json_decode($url, true);
    print_r($jsonObj);


}

//Percorre o arquivo xml
foreach($jsonObj['rows'] as $distance) {
    echo 'A distancia para voce é de : ' . $distance['elements'][0]['distance']['text'];
}

The idea is that inside the foreach it computes the distance of more than one place.

    
asked by anonymous 07.07.2016 / 00:44

1 answer

1

You have to encode the data passed to querystring, so use urlencode or rawurlencode like this:

foreach ($dados as $rua) {
    //Faz a requisicao do arquivo xml

    $rua = rawurlencode($rua);

    $url = file_get_contents("https://maps.googleapis.com/maps/api/distancematrix/json?origins=".$rua."|Brasil&destinations=AmadorBuenoDaVeiga|Brasil&mode=car&language=pt-BR");
    $jsonObj = json_decode($url, true);
    print_r($jsonObj);


}

You can also use http_build_query like this:

$data = array(
          'destinations' => 'AmadorBuenoDaVeiga|Brasil',
          'mode'         => 'car',
          'language'     => 'pt-BR',
        );

$url = 'https://maps.googleapis.com/maps/api/distancematrix/json?';

foreach ($dados as $rua) {
    $data['origins'] = $rua. '|Brasil';

    $querystring = http_build_query($data);

    $url = file_get_contents($url . $querystring);

    $jsonObj = json_decode($url, true);

    print_r($jsonObj);
}

Documentation:

09.07.2016 / 02:43