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

如何在Google Actions中获取用户设备经纬度?@assistant/conversation相关疑问

获取用户设备地理位置(@assistant/conversation 实现)

好问题!其实@assistant/conversation完全支持获取用户设备的地理位置,不需要退回到旧版actions-on-google库。我来给你梳理下具体的实现步骤:

1. 在Actions Console配置权限

首先得在Google Actions控制台里开启对应的位置权限:

  • 进入你的项目后台,点击左侧菜单的Settings -> Permissions
  • 点击Add permission,选择DEVICE_PRECISE_LOCATION(精确位置)或DEVICE_COARSE_LOCATION(粗略位置),根据你的需求添加
  • 保存配置,确保权限已启用

2. 在代码中实现权限请求与位置获取

接下来用@assistant/conversation库编写逻辑,分为请求权限、处理授权后的位置数据两个核心步骤。

安装依赖

首先确保你已经安装了官方库:

npm install @assistant/conversation

代码示例

const { conversation } = require('@assistant/conversation');
const app = conversation({ debug: true });

// 触发位置权限请求的处理器
app.handle('request_location_intent', conv => {
  // 请求精确位置权限,可替换为DEVICE_COARSE_LOCATION
  conv.permissions.request('DEVICE_PRECISE_LOCATION');
});

// 用户授权后处理位置数据的处理器
app.handle('handle_location_intent', conv => {
  // 检查是否成功获取到位置坐标
  if (conv.device.location?.coordinates) {
    const { lat, lng } = conv.device.location.coordinates;
    conv.add(`已获取到你的位置:纬度 ${lat},经度 ${lng}`);
  } else {
    conv.add('抱歉,我没能获取到你的位置信息,请检查是否已授权');
  }
});

// 处理用户拒绝权限的情况
app.handle('permission_denied_intent', conv => {
  conv.add('没关系,如果你之后需要位置服务,可以随时告诉我');
});

exports.ActionsOnGoogleFulfillment = app;

3. 关联对话流程与处理器

在Actions Console的Build -> Actions(或对话构建器)里完成配置:

  • 创建一个自定义意图(比如request_location_intent),当用户说出类似"告诉我我的位置"这类触发词时,调用对应的权限请求处理器
  • 找到系统内置的actions_intent_PERMISSION意图,将其关联到handle_location_intent(用户授权后自动触发)
  • 可选:配置用户拒绝权限后的处理逻辑,关联到permission_denied_intent

注意事项

  • 测试时需要在Google Assistant模拟器或真实设备上进行,因为权限请求必须用户手动交互授权
  • 确保你的 fulfillment 服务已经正确部署并关联到Actions项目
  • 如果用户多次拒绝权限,建议提供替代方案,避免影响整体用户体验

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.05.09 21:37:59