Hey all,
I’m trying to work with the Google Maps Distance Matrix API using cURL. Here’s my code:
[php]
public function get_travel($lat, $lon) {
$pdx_lat = '45.579030';
$pdx_lon = '-122.635391';
$portland_api_url = "https://maps.googleapis.com/maps/api/distancematrix/json?origins=" . $pdx_lat . ", " . $pdx_lon . "&destinations=" . $lat . ", " . $lon . "&mode=car&language=en-EN&units=imperial";
$ch = curl_init();
curl_setopt($ch, CURLOPT_URL, $portland_api_url);
curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1);
$data_decoded = json_decode(curl_exec($ch), true);
$distance = $data_decoded['rows']['elements']['distance']['text'];
$duration = $data_decoded['rows']['elements']['duration']['text'];
$travel_data = [$distance, $duration];
return $travel_data;
}
[/php]
Problem is I can’t get the cURL to work properly. When I bypass the variable assignment from the resulting array and just try to var_dump of $data_decoded I get a null. What am I doing wrong in the cURL?
Here’s the result if I plug the url directly into a browser:
{
"destination_addresses" : [ "1400 Newmark Ave, Coos Bay, OR 97420, USA" ],
"origin_addresses" : [ "Portland, OR, USA" ],
"rows" : [
{
"elements" : [
{
"distance" : {
"text" : "224 mi",
"value" : 360089
},
"duration" : {
"text" : "3 hours 54 mins",
"value" : 14048
},
"status" : "OK"
}
]
}
],
"status" : "OK"
}