超过查询限制也使用setTimeout

时间:2014-03-23 12:14:18

标签: google-maps google-maps-api-3

我试图使用谷歌地图地理编码器并超过查询限制。 这是我的代码

var geocoder;
var map;
function initialize() {
    geocoder = new google.maps.Geocoder();
    var latlng = new google.maps.LatLng(-34.397, 150.644);
    var mapOptions = {
        zoom: 12,
        center: latlng
    }
    map = new google.maps.Map(document.getElementById('map-canvas'), mapOptions);
}
function codeAddress() {
    for (var i = 1; i < 20; i++) {
        var address = document.getElementById('address' + " " + i).value;
        setTimeout(geocoder.geocode({ 'address': address }, function (results, status) {
            if (status == google.maps.GeocoderStatus.OK) {
                map.setCenter(results[0].geometry.location);
                var marker = new google.maps.Marker({
                    map: map,
                    position: results[0].geometry.location
                });
            } else {
                alert('Geocode was not successful for the following reason: ' + status);
            }
        }));
    }
}
google.maps.event.addDomListener(window, 'load', initialize, codeAddress.bind);

1 个答案:

答案 0 :(得分:0)

您没有指定延迟(setTimeout的第二个参数)

您必须将其设置为递增值以避免错误,例如i*150,然后调用将在150ms,300ms,450ms之后等等

function codeAddress() {
    for (var i = 1; i < 20; i++) {
        var address = document.getElementById('address' + " " + i).value;
        setTimeout(geocoder.geocode({ 'address': address }, 
          function (results, status) {
            if (status == google.maps.GeocoderStatus.OK) {
                map.setCenter(results[0].geometry.location);
                var marker = new google.maps.Marker({
                    map: map,
                    position: results[0].geometry.location
                });
            } else {
                alert('Geocode was not successful for the following reason: ' +
                       status);
            }
        }),
        i*150//<-delay for the timeout   in ms
        );

    }
}