调用Google地理编码API遇权限及Geometry读取错误求助
谷歌地理编码/定位API错误排查与解决
错误1:Uncaught (in promise) Error at _.se.captureStackTrace
原因
Promise拒绝未被捕获,axios请求失败时没有对应的错误处理逻辑,导致抛出未处理的Promise错误。
修复
在请求链末尾添加错误捕获逻辑,或者改用谷歌Maps JavaScript API内置的地理编码服务(更适配浏览器端场景)。
错误2:API keys with referer restrictions cannot be used with this API
原因
你的API密钥设置了HTTP引用限制,但直接通过axios调用Geocoding API属于跨域请求,若当前页面域名不在密钥允许的引用列表里,或者密钥限制类型与使用场景不匹配,就会触发该错误。
修复
- 登录谷歌云控制台调整API密钥设置:
- 浏览器端使用时,将密钥的应用限制设为
HTTP引用(网站),并添加当前页面的域名(例如https://yourdomain.com/*) - 替换axios调用方式,改用谷歌Maps JavaScript API提供的
google.maps.Geocoder服务,它会自动适配浏览器端的密钥规则
- 浏览器端使用时,将密钥的应用限制设为
错误3:Uncaught (in promise) TypeError: Cannot read properties of undefined (reading 'geometry')
原因
response.data.results[0]不存在:地址解析失败、请求出错时,results数组为空latLngB中的a和b未定义:showPosition函数未实现,未获取到当前位置的经纬度
修复
- 先判断地理编码返回的results是否有数据,再访问geometry属性
- 实现
showPosition函数,存储当前位置的经纬度
修改后的完整代码
头部代码
<script async defer src="https://maps.googleapis.com/maps/api/js?key=MyAPIKey&callback=initMap&v=beta&libraries=geometry"></script>
主体代码
// 存储当前位置经纬度 let currentLat, currentLng; function showPosition(position) { currentLat = position.coords.latitude; currentLng = position.coords.longitude; // 获取到位置后执行距离计算 window.calculateDistance(); } function calculateDistance(id, addy, city, state) { const x = document.getElementById(id); if (!currentLat || !currentLng) { x.innerHTML = "无法获取当前位置"; return; } const geocoder = new google.maps.Geocoder(); const location = `${addy} ${city} ${state}`; geocoder.geocode({ address: location }, (results, status) => { if (status === "OK" && results.length > 0) { const latLngA = results[0].geometry.location; const latLngB = new google.maps.LatLng(currentLat, currentLng); const distanceKm = (google.maps.geometry.spherical.computeDistanceBetween(latLngA, latLngB) / 1000).toFixed(2); x.innerHTML = `${distanceKm}km`; } else { x.innerHTML = `地址解析失败:${status}`; console.error("地理编码错误:", status); } }); } function initMap(id, addy, city, state) { const x = document.getElementById(id); if (navigator.geolocation) { navigator.geolocation.getCurrentPosition(showPosition, (error) => { x.innerHTML = `获取位置失败:${error.message}`; }); } else { x.innerHTML = "浏览器不支持地理定位"; } // 传递参数给计算函数 window.calculateDistance = () => calculateDistance(id, addy, city, state); } window.initMap = initMap;
关键修改点
- 改用
google.maps.Geocoder替代axios,适配浏览器端密钥限制 - 实现
showPosition函数,处理当前位置获取逻辑 - 增加错误判断:检查地理编码状态、results是否为空
- 给
getCurrentPosition添加错误回调,处理定位失败情况 - 移除不必要的axios依赖,直接使用Maps JS API原生服务
内容的提问来源于stack exchange,提问作者Mpilonhle Ngcoya
相关产品推荐
相关产品推荐

