接入Google Time Zone API实现用户时区展示功能异常求助
问题原因
- 同名函数冲突:定义了两个都叫
showPosition的函数,JS运行时后定义的函数会覆盖前者,导致只有一个逻辑能生效 - 时区API参数错误:
- Google Time Zone API需要三个必填参数:
location(经纬度)、timestamp(Unix时间戳,单位秒)、key(你的API密钥),你当前把key错填到了timestamp参数的位置 - 参数拼接用了HTML转义符
&,JS字符串中直接用&即可,否则参数会被错误解析
- Google Time Zone API需要三个必填参数:
- 逻辑链路缺失:没有在反向地理编码执行完成后主动调用时区获取的逻辑,两个功能是独立的没有关联
- 语法错误:JS代码末尾多了一个多余的闭合大括号,会触发语法报错
修正方案
调整后的JS代码
var x = document.getElementById('output'); function getLocation(){ if (navigator.geolocation){ x.innerHTML = "Supporting"; navigator.geolocation.getCurrentPosition(showPosition); } else{ x.innerHTML = "Browser not supporting"; } } // 新增时区获取函数,改名避免冲突 function getTimezone(location) { // 生成当前Unix时间戳,单位秒 const timestamp = Math.floor(Date.now() / 1000); // 替换<你的API密钥>为你实际的Google API密钥 var timeAPI = "https://maps.googleapis.com/maps/api/timezone/json?location="+location.coords.latitude.toFixed(6)+","+location.coords.longitude.toFixed(6)+"×tamp="+timestamp+"&key=<你的API密钥>"; $.get({ url:timeAPI, success:function(data){ console.log(data); // 把时区信息写到页面 x.innerHTML += "<br/>时区:" + data.timeZoneName + "(" + data.timeZoneId + ")"; } }); } function showPosition(position){ // 替换<你的API密钥>为你实际的Google API密钥 var locAPI = "https://maps.googleapis.com/maps/api/geocode/json?latlng="+position.coords.latitude.toFixed(6)+","+position.coords.longitude.toFixed(6)+"&key=<你的API密钥>"; $.get({ url: locAPI, success: function(data){ console.log(data); const num = 0; var add1 = data.results[num].address_components.length - 1; var add2 = data.results[num].address_components.length - 2; x.innerHTML = data.results[num].address_components[add2].long_name; x.innerHTML += "<br/>"; x.innerHTML += data.results[num].address_components[add1].long_name; // 地理编码获取成功后调用时区接口 getTimezone(position); } }); }
注意事项
- 确保你的Google API密钥已经同时开启了Geocoding API和Time Zone API的访问权限
- 本地测试时建议用localhost域名,Google API对本地调试有特殊兼容规则
- 生产环境需要给API密钥配置HTTP referer限制,避免被盗刷
内容的提问来源于stack exchange,提问作者Methsara Perera
相关产品推荐
相关产品推荐

