如何推迟谷歌地理编码?

时间:2016-10-04 14:39:39

标签: javascript google-maps settimeout geocoding

我试图通过循环邮政编码从json文件中对大约100个邮政编码进行地理编码,但是在11个邮政编码后我受到OVERY_QUERY_LIMIT错误的限制。我似乎每秒使用地理编码器太快了。我已经尝试将setTimeout合并到它中但是可以使它工作。我怎样才能放慢这个过程?

<head>
    <meta charset="UTF-8">
    <title>heatmap test</title>

    <style>
        html {
            height: 100%
        }

        body {
            height: 100%;
            margin: 0;
            padding: 0;
            font-family: sans-serif;
        }

        #map-canvas {
            height: 100%
        }
    </style>
</head>

<body>
    <div id="map-canvas"></div>

    <script src="https://maps.googleapis.com/maps/api/js"></script>
    <script src="assets/gmaps.js"></script>
    <script>
        document.addEventListener("DOMContentLoaded", function (event) {

                var getPostcodes = function () {

                    //json link
                    var json = "http://localhost/addresses.json/";

                    var request = new XMLHttpRequest();
                    request.open('GET', json, true);

                    request.onload = function () {
                        if (request.status >= 200 && request.status < 400) {
                            // Success!
                            var data = JSON.parse(request.responseText);

                            //GET POSTCODES IN ARRAY
                            var postcodesArray = [];
                            for (var i = 0; i < data.length; i++) {
                                postcodesArray.push(data[i].from_postcode);
                            }

                            //filter all falsey values from array
                            var postcodes = postcodesArray.filter(Boolean);

                            //creating object for inserting data
                            var testData = {
                                data: []
                            };

                            //GET LAT/LONG POSITIONS
                            //for loop to create geocode object for each postcode
                            for (var n = 0; n < postcodes.length; n++) {

                                setTimeout(function(){

                                GMaps.geocode({
                                    address: postcodes[n],
                                    callback: function (results, status) {
                                        if (status == google.maps.GeocoderStatus.OK) {
                                            var location = results[0].geometry.location;

                                            var latitude = parseFloat(location.lat().toFixed(8)),
                                                longitude = parseFloat(location.lng().toFixed(8));

//                                            pushing lat and long data to object
                                            testData.data.push({
                                                lat: latitude,
                                                lng: longitude
                                            });
                                        } else if (status === google.maps.GeocoderStatus.OVER_QUERY_LIMIT) {
                                            console.log("error");
                                        }

                                    }

                                });

                                }, 500);
                            }

                            console.log(testData);
                        }
                        else {
                            console.log("failed");
                        }
                    };
                    request.onerror = function () {
                        // There was a connection error of some sort
                    };
                    request.send();
                }

                getPostcodes();

            });
    </script>
</body>

1 个答案:

答案 0 :(得分:1)

SetTimeout simply delays code, and you've given the timeout a set delay.

What happens is all of your functions wait for 500ms and then all get run instantly.

What you can either do is have a dynamic delay like so:

...

for (var n = postcodes.length; n--;) {
    setTimeout(function(){
        GMaps.geocode({
            ...
        })
    }, 500 * n);
}

....

or use a setInterval, but the above code would work best. The setInterval would make less sense.

相关问题