Google Maps Geocoder报REQUEST_DENIED错误,求代码修复方案
解决Google Maps Geocode的「REQUEST_DENIED」错误及修改后的完整代码
嘿,我来帮你搞定这个困扰已久的问题!你碰到的「Geocoder failed due to: REQUEST_DENIED」错误,九成都是API密钥的配置问题,咱们一步步排查修复:
错误原因分析
这个错误主要由以下几种情况导致:
- 代码里的
MY_API_KEY是占位符,没有替换成你自己在Google Cloud Console生成的有效API密钥 - 你的API密钥没有启用「Geocoding API」服务
- 密钥的使用限制设置不当(比如HTTP referrers限制的域名和当前运行环境不匹配)
修改后的完整代码
下面是修复后的代码,重点注意标记的API密钥部分,记得替换成你自己的有效密钥:
<!DOCTYPE html> <html> <head> <style> /* Always set the map height explicitly to define the size of the div element that contains the map. */ #map { height: 100%; } /* Optional: Makes the sample page fill the window. */ html, body { height: 100%; margin: 0; padding: 0; } #floating-panel { position: absolute; top: 5px; left: 50%; margin-left: -180px; width: 350px; z-index: 5; background-color: #fff; padding: 5px; border: 1px solid #999; } #latlng { width: 225px; } </style> </head> <body> <div id="floating-panel"> <input id="latlng" type="text" value="40.714224,-73.961452"> <input id="submit" type="button" value="Reverse Geocode"> </div> <div id="map"></div> <script> function initMap() { var map = new google.maps.Map(document.getElementById('map'), { zoom: 8, center: {lat: 40.731, lng: -73.997} }); var geocoder = new google.maps.Geocoder; var infowindow = new google.maps.InfoWindow; document.getElementById('submit').addEventListener('click', function() { geocodeLatLng(geocoder, map, infowindow); }); } function geocodeLatLng(geocoder, map, infowindow) { var input = document.getElementById('latlng').value; var latlngStr = input.split(',', 2); var latlng = {lat: parseFloat(latlngStr[0]), lng: parseFloat(latlngStr[1])}; geocoder.geocode({'location': latlng}, function(results, status) { if (status === 'OK') { if (results[0]) { map.setZoom(11); var marker = new google.maps.Marker({ position: latlng, map: map }); infowindow.setContent(results[0].formatted_address); infowindow.open(map, marker); } else { window.alert('No results found'); } } else { window.alert('Geocoder failed due to: ' + status); } }); } </script> <!-- 替换这里的YOUR_ACTUAL_API_KEY为你在Google Cloud Console生成的有效密钥 --> <script src="https://maps.googleapis.com/maps/api/js?key=YOUR_ACTUAL_API_KEY&callback=initMap" async defer></script> </body> </html>
额外配置步骤(必须做!)
- 登录Google Cloud Console,找到你的API密钥
- 确保「Geocoding API」已经被启用(在API库中搜索并启用)
- 如果你是本地测试,可以暂时把密钥的「应用限制」设置为「无」(上线后再根据实际域名设置HTTP referrers限制)
这样修改后,应该就能正常使用反向地理编码功能了!
内容的提问来源于stack exchange,提问作者Arnav Nath
相关产品推荐
相关产品推荐

