Error 400 Bad Request in Google Distance Calculation API

Asked

Viewed 943 times

0

This is the Error that is happening at the time of Sending Requests by 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 only happens when I loop the 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 he calculates the distance of more than one place.

1 answer

1


You have to encode the data passed to querystring, for this use urlencode or rawurlencode thus:

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 the http_build_query thus:

$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:

  • 1

    Thank you very much William worked !

Browser other questions tagged

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