devShuba
devShuba

Reputation: 91

Can't get JSON data from Google Maps request with cuRL

I'm trying to write a request with curl. I want to get the distance between two points. Therefore I'm getting the data of those points from my db to build the string. The final string looks like this when I echo it.

http://maps.googleapis.com/maps/api/distancematrix/json?origins=40215+Düsseldorf+Königsallee 59&destinations=40215+Düsseldorf&sensor=false

I also tried it with https instead of http but the result was the same.

As you can see, it returns a perfectly fine JSON-Response, but when I do this afterwards, I always get an error.

public function request($signedUrl) {
        $ch = curl_init($signedUrl);
        curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
        curl_setopt($ch, CURLOPT_HEADER, 0);
        $data = curl_exec($ch);
        curl_close($ch);
        $this->response = json_decode($data);
    }

The $signedUrl is the requestUrl.

The error from Google I get, when I var_dump($data) is

400. That’s an error.

Your client has issued a malformed or illegal request. That’s all we know. "

When I var_dump the response, it just gives me null.

What could be the problem here and how could I fix it? I also tried to read it in with file_get_contents but without success

Upvotes: 2

Views: 2786

Answers (1)

Works [Tested] . You got a bad request since the URL was not encoded.

<?php
$urlx='http://maps.googleapis.com/maps/api/distancematrix/json?origins=40215+D%C3%BCsseldor%20%E2%80%8Bf+K%C3%B6nigsallee59&destinations=40215+D%C3%BCsseldorf&sensor=false';
$ch = curl_init($urlx);
curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
curl_setopt($ch, CURLOPT_HEADER, 0);
$data = curl_exec($ch);
curl_close($ch);
var_dump(($data));

Upvotes: 4

Related Questions