You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

Android端Google Directions API授权失败,无法生成路线求助

解决Android调用Google Directions API返回REQUEST_DENIED的问题

核心问题分析

你遇到的REQUEST_DENIED错误说明API项目未被授权使用Directions API,尽管密钥能在Web端JS SDK和Android Map SDK正常工作,但Directions API是独立的Google Web服务API,需要单独配置。

排查与解决步骤

1. 确认Google Directions API已启用

登录Google Cloud控制台,搜索Directions API(注意区分Maps SDK for Android、Maps JavaScript API),确保该API状态为「已启用」。即使开启了其他Maps相关API,独立的Directions API仍需单独激活。

2. 检查API密钥的限制与计费配置

  • 若密钥设置了Android应用限制:确认已添加当前应用的SHA-1证书指纹和包名,debug、release环境的SHA-1需分别配置,且信息完全匹配。
  • 若密钥为无限制状态:确认项目已绑定有效支付方式(Google Web服务API需启用计费,即使使用免费额度也需完成支付方式绑定)。

3. 修正API请求参数编码

当前代码直接拼接坐标参数,可能因特殊字符导致请求异常,修改getDirectionsUrl方法添加URL编码:

public static String getDirectionsUrl(LatLng origin, LatLng destination, String apiKey) {
    try {
        String originStr = URLEncoder.encode(origin.latitude + "," + origin.longitude, "UTF-8");
        String destStr = URLEncoder.encode(destination.latitude + "," + destination.longitude, "UTF-8");
        String url = "https://maps.googleapis.com/maps/api/directions/json?" +
                "origin=" + originStr +
                "&destination=" + destStr +
                "&mode=driving&key=" + apiKey;
        System.out.println("Directions API URL: " + url);
        return url;
    } catch (UnsupportedEncodingException e) {
        e.printStackTrace();
        return null;
    }
}

4. 优化响应解析逻辑

当前代码仅通过routes长度判断结果,无法捕获授权类错误,建议先校验API返回的status字段:

public static List<LatLng> parseDirectionsResponse(String response) throws JSONException {
    JSONObject jsonObject = new JSONObject(response);
    String status = jsonObject.getString("status");
    if (!"OK".equals(status)) {
        String errorMsg = jsonObject.optString("error_message", "Unknown error");
        Log.e("DirectionsApi", "API request failed: " + status + " - " + errorMsg);
        return null;
    }
    // 原有解析逻辑...
}

修改后可在日志中直接看到授权失败的具体原因,便于定位问题。

5. 直接测试请求URL

复制代码中打印的Directions API URL,在浏览器中直接访问:

  • 若浏览器返回相同错误,说明问题出在API项目配置,而非代码;
  • 若浏览器访问正常,检查Android端网络配置(如代理、防火墙拦截)。

内容的提问来源于stack exchange,提问作者Gautam chibi

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.06.22 06:14:53