如何避免Google Maps JavaScript API出现问题?

时间:2016-06-19 09:57:07

标签: javascript google-maps-api-3

我正在将Google Maps JavaScript API与api密钥结合使用。这适用于几个小时或几天,但在特定的间隔后,我收到以下403错误,地图消失了:

enter image description here

我不知道问题出在哪里,因为我还没有达到每天25.000个请求。如果我重置api密钥并重新加载页面,地图再次正确加载,但我不想一次又一次地重置api密钥。

正如您所看到的,我正在使用自定义地图,但我认为代码不是问题,但这里是代码:

(function(window, google){

    var infoWindow = null;

    function init() {
        var map;
        var mapOptions = {
            zoom: 12,
            scrollwheel: false,
            center: new google.maps.LatLng(
                51.050409,
                13.737262
            ),
            mapTypeId: google.maps.MapTypeId.ROADMAP
        };
        map = new google.maps.Map(
            document.getElementById('map'),
            mapOptions
        );
        setMarkers(map, locations);
        infoWindow = new google.maps.InfoWindow({
            content: "holding..."
        });
    }

    function setMarkers(map, locations) {
        var i, icon, marker, contentString;
        for (i = 0; i < locations.length; i++) {
            icon = '../Images/icn-marker.png';
            contentString = '<div><b>' + locations[i][0] + '</b><br>' + locations[i][1] + '<br>' + locations[i][4] + '</div>';
            marker = new google.maps.Marker({
                position: new google.maps.LatLng(locations[i][2], locations[i][3]),
                map: map,
                title: locations[i][0],
                icon: icon,
                html: contentString
            });
            google.maps.event.addListener(marker, 'click', function() {
                infoWindow.setContent(this.html);
                infoWindow.open(map, this);
            });
        }
    }

    google.maps.event.addDomListener(window, 'load', init);

})(window, google);

我的任何脚本包含如下内容:

<script src="https://maps.googleapis.com/maps/api/js?key=MYAPIKEY"></script>
<script src="http://example.de/example/map.js"></script>

希望你能帮忙,因为我不会&#39;知道问题所在。

1 个答案:

答案 0 :(得分:0)

403 error响应表示您的API密钥无效或未包含在请求中。请确认您已包含整个密钥,并且您已为此密钥启用了API。

此外,检查您的usage limit,如果超出使用限制或以其他方式滥用服务,Web服务将返回特定的错误消息。如果继续超出限制,则可能会阻止您访问Web服务。也可以收到403 Forbidden response。

通过结合两种方法可以解决问题:

  • 通过优化应用程序以更有效地使用Web服务来降低使用率。
  • 在可能的情况下,通过为您的Google Maps API for Work许可购买额外的限额来提高使用限制。

注意: 请求失败时,应确保使用指数退避重试请求。例如,如果请求失败一次,则在一秒后重试,如果再次失败,则在两秒后重试,然后重试四秒,依此类推。这可以确保破坏的请求或大规模的故障不会淹没Google的服务器,因为许多客户尝试非常快速地重试请求。

此处有相关的SO票据遇到403错误回复:Google static map API getting 403 forbidden when loading from img tag

相关问题