Google map api directions service gives OVER_QUERY_LIMIT while displaying route between multiple markers javascript

后端 未结 1 416
无人及你
无人及你 2020-12-11 14:01

I\'m working with the project which has driver tracking module. I\'ve lat/long in my database, I\'m fetching it on date and username.

The current implementation is

相关标签:
1条回答
  • 2020-12-11 14:14

    I think you can easily find an answer and explanation in the official documentation of Maps JavaScript API:

    https://developers.google.com/maps/documentation/javascript/usage

    Service requests are rate-limited per user session, regardless of how many users share the same project. When you first load the service API, you are allocated an initial quota of requests. Once you use this quota, the API enforces rate limits on additional requests on a per-second basis. If too many requests are made within a certain time period, the API returns an OVER_QUERY_LIMIT response code. The per-session rate limit prevents the use of client-side services for batch requests. For batch requests, use the Maps API web services.

    That means when you load the page you have an initial bucket of requests for directions service (I believe this is 10 requests), once you have used 10 initial requests you can execute only 1 request per second. So, you have to wait one second before execution of the each next directions request.

    The code snippet might be something similar to

    var delayFactor = 0;
    
    function m_get_directions_route (request) {
        directions.route(request, function(result, status) {
            if (status === google.maps.DirectionsStatus.OK) {
                //Process you route here
            } else if (status === google.maps.DirectionsStatus.OVER_QUERY_LIMIT) {
                delayFactor++;
                setTimeout(function () {
                    m_get_directions_route(request);
                }, delayFactor * 1000);
            } else {
                console.log("Route: " + status);
            }
        });
    } 
    
    for (var i = 0; i < lat_lng.length; i++) {
        if ((i + 1) < lat_lng.length) {
            var src = lat_lng[i];
            var des = lat_lng[i + 1];
    
            var request = {
                origin: src,
                destination: des,
                travelMode: google.maps.DirectionsTravelMode.DRIVING
            };
    
            m_get_directions_route (request);
        }
    }
    

    With this code ten requests will be executed immediately and following requests will be executed after 1, 2, 3, ... seconds.

    0 讨论(0)
提交回复
热议问题