从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
相关产品推荐
相关产品推荐

