Google Maps discontinued Directions and DistanceMatrix a couple of weeks ago and I am trying to adapt CURL code in PHP to switch over to the Routes API. There does not seem to yet be any handy pre-written examples in PHP to copy. Here's what I have:
$service_url = ':computeRoutes';
$curl = curl_init($service_url);
$curl_post_data = array(
'origin' => '1665 Cottage St SE, Salem, OR',
'destination' => '840 Judson St SE, Salem, OR',
'travelMode' => 'DRIVE',
'fieldMask' => 'routes.duration,routes.distanceMiles',
'units' => 'IMPERIAL'
);
$json_post_data=json_encode($curl_post_data);
$apiKey='--my api key is inserted here--';
curl_setopt($ch, CURLOPT_HTTPHEADER, array(
'Content-Type: application/json',
'X-Goog-Api-Key:'.$apiKey
));
curl_setopt($curl, CURLOPT_RETURNTRANSFER, true);
curl_setopt($curl, CURLOPT_POST, true);
curl_setopt($curl, CURLOPT_POSTFIELDS, $json_post_data);
$curl_response = curl_exec($curl);
if ($curl_response === false) {
$info = curl_getinfo($curl);
curl_close($curl);
die('error occurred during curl exec. Additional info: ' . var_export($info));
}
curl_close($curl);
$decoded = json_decode($curl_response);
if (isset($decoded->response->status) && $decoded->response->status == 'ERROR') {
die('error occured: ' . $decoded->response->errormessage);
}
echo 'response ok!<br />';
var_export($decoded->response);
print_r($decoded);
The response is:
Method doesn't allow unregistered callers (callers without established identity). Please use API Key or other form of API consumer identity to call this API.
But the API key is in the header as seems to be the requirement, as far as I can tell.