Google Maps Routes API调用时API Key不被识别的问题排查
问题解决思路
核心错误1:CURL句柄变量名不一致
你初始化CURL时用的是$curl = curl_init($service_url);,但设置请求头的时候却用了未定义的$ch变量,导致X-Goog-Api-Key根本没被加到请求里,这是触发身份验证错误的直接原因。
核心错误2:请求体格式不符合Routes API要求
Routes API的origin和destination不能直接传字符串地址,需要用结构化对象格式,比如通过address字段指定地址,或用location指定经纬度。
修正后的完整代码
<?php $service_url = 'https://routes.googleapis.com/directions/v2:computeRoutes'; // 统一CURL句柄变量 $curl = curl_init($service_url); // 修正请求体格式 $curl_post_data = [ 'origin' => [ 'address' => '1665 Cottage St SE, Salem, OR' ], 'destination' => [ 'address' => '840 Judson St SE, Salem, OR' ], 'travelMode' => 'DRIVE', 'fieldMask' => 'routes.duration,routes.distanceMiles', 'units' => 'IMPERIAL' ]; $json_post_data = json_encode($curl_post_data); $apiKey = '--你的API密钥--'; // 用正确的$curl变量设置请求头 curl_setopt($curl, CURLOPT_HTTPHEADER, [ 'Content-Type: application/json', 'X-Goog-Api-Key: ' . $apiKey, // 可选:添加该头指定返回字段,做双重保障 'X-Goog-FieldMask: routes.duration,routes.distanceMiles' ]); 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('CURL执行出错,详情:' . var_export($info, true)); } curl_close($curl); $decoded = json_decode($curl_response); // 调整错误判断逻辑,Routes API错误格式与旧版不同 if (isset($decoded->error)) { die('API请求出错:' . $decoded->error->message); } echo '请求成功!<br />'; print_r($decoded); ?>
额外注意事项
- 确保你的API密钥已在Google Cloud控制台启用Routes API服务。
fieldMask需准确指定返回字段,避免冗余数据,也可通过请求头X-Goog-FieldMask重复指定。
内容的提问来源于stack exchange,提问作者D Yates
相关产品推荐
相关产品推荐

