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

从Google Geocoding API获取嵌套JSON值:geometry属性显示undefined

解决Google Geocoding API访问geometry显示undefined的问题

嘿,这问题我太熟了!你之所以碰到response.results.geometry返回undefined的情况,核心原因是没注意到Google返回的results是数组类型——看你贴的JSON里"results" : [ ... ]的方括号就明白啦!数组本身并没有geometry这个属性,你得先从数组里取出具体的结果对象才行。

正确的访问方式

通常地理编码的第一个结果就是最匹配的,所以你可以先取数组的第一个元素,再访问它的geometry属性:

// 先获取第一个匹配结果
const matchedResult = response.results[0];
// 现在就能正常访问geometry了
const locationGeometry = matchedResult.geometry;

// 举个实际例子,提取经纬度
const latitude = locationGeometry.location.lat;
const longitude = locationGeometry.location.lng;

更稳妥的写法(避免空数组报错)

为了防止没有匹配结果导致报错,最好先判断数组是否有内容:

if (response.results && response.results.length > 0) {
  const geometry = response.results[0].geometry;
  // 在这里处理你的地理数据逻辑
} else {
  console.log("没有找到符合条件的地理编码结果哦");
}

再回头看你贴的JSON片段,results数组里的每一个对象才包含address_components、geometry这些属性,直接给数组加.geometry自然会返回undefined啦~

内容的提问来源于stack exchange,提问作者J. Doe

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.05.26 10:20:11