Cors Api Google Maps

Asked

Viewed 221 times

1

I am developing a system made in Silex/PHP and his frontend is being done in Angularjs, I have a method in it that I am wanting him to do a search in the Google Maps API to return me a certain route, but every time returns me the following error:

inserir a descrição da imagem aqui The header of the request:

inserir a descrição da imagem aqui

If I enable Cors with the Chrome extension works perfectly:

inserir a descrição da imagem aqui

I have an index.php where all requests go through it, so insert the following:

inserir a descrição da imagem aqui

I’ve tried everything but nothing works, someone’s been through it ?

  • No use adding CORS headers to your website, the browser will check them at the API address, ie at the Google address, which you have no control over. What you need is to see the google API manual to see what is incorrect, but the little I’ve read already say that the use of Distance Matrix is prohibited by google for any use other than displaying the information on a google map.

  • But if I take the url and paste it into the browser it returns me the normal xml or json.

  • This is because you opened the URL in the browser manually, by ajax is different, the browser blocks ajax requests between different domains unless it releases the access by CORS. And as I said, you should check the Google Apis manual, there you should find how to do it correctly, including acquiring an access key that Google uses to control access to its Apis and in which cases you may or may not use its Apis.

  • Leandro, OK. I’ll check here.

  • Leandro could not yet, but only a doubt if I enable Chrome cross origin it works !

  • Make no mistake, what this extension does is disable the browser security feature, it makes the browser work as if the server responded with CORS headers, this should never be used as a reference to create a program.

Show 1 more comment

1 answer

0


The Google API does not support either CORS or JSONP, so you’ll have to proxy with php. Something like this:

$http.get('goog.php').then(
    function(res){
        console.info(res);
        if(res.status == 200){

        }
    }, function(error){
        //mensagem de erro
        console.info(error);
    }
);

PHP:

<?php
$url = 'https://maps.googleapis.com/maps/api/distancematrix/json?origins=Vancouver+BC|Seattle&destinations=San+Francisco|Victoria+BC&mode=bicycling&language=fr-FR&key=SUA_KEY';
$returned_content = get_data($url);

header('Content-Type: application/json');
echo $returned_content;

function get_data($url) {
    $ch = curl_init();
    $timeout = 5;
    curl_setopt($ch, CURLOPT_URL, $url);
    curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1);
    curl_setopt($ch, CURLOPT_CONNECTTIMEOUT, $timeout);
    $data = curl_exec($ch);
    curl_close($ch);
    return $data;
}
?>

If you don’t have curl, uses some other way.

Browser other questions tagged

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