异步和等待

Async and await

我想为邮政编码绘制标记。但我只能看到几个标记。 我以为是async和await的原因,但是不知道加到哪里。 有人请帮助我。

var zipCode=[...]; //zipCode is array of zip codes.
function func1() {
    zipCode.forEach((item, index) => {
        drawZipCodeMarker(item.zip);
    });
}


function drawZipCodeMarker(zip){
       geocoder.geocode({'address':zip}, (results, status) => {
            console.log(zip);
            console.log(results);
            if (results != null) {
                var temp = new google.maps.Marker({position : results[0].geometry.location, map:map, title:zip});
            }
        });
    }

您正在使用地图的地理编码服务 JavaScript API。 Google Maps JavaScript API 中的服务具有文档中描述的每次会话限制。

Note: The additional rate limit is applied per user session, regardless of how many users share the same project. When you first load the 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, such as batch geocoding. For batch requests, use the Geocoding API web service.

来源:https://developers.google.com/maps/documentation/javascript/geocoding

据我所知,最初您有 10 个请求。一旦桶为空,请求将被拒绝。桶以每秒 1 个请求的速率重新填充。因此,您必须限制您的地理编码请求,以保持在每个会话允许的限制范围内。

您应该检查回复的状态。如果状态为 OVER_QUERY_LIMIT,那么您已用完存储桶并需要重试请求。您可以使用指数退避方法重试逻辑 (https://en.wikipedia.org/wiki/Exponential_backoff)。

var zipCode=[...]; //zipCode is array of zip codes.
var delayFactor = 0;

function func1() {
    zipCode.forEach((item, index) => {
        drawZipCodeMarker(item.zip);
    });
}

function drawZipCodeMarker(zip) {
   geocoder.geocode({'address':zip}, (results, status) => {
       if (status === google.maps.GeocoderStatus.OK) {
           console.log(zip);
           console.log(results);
           if (results != null) {
               var temp = new google.maps.Marker({position : results[0].geometry.location, map:map, title:zip});
           }
       } else if (status === google.maps.GeocoderStatus.OVER_QUERY_LIMIT) {
           delayFactor++;
           setTimeout(function () {
               drawZipCodeMarker(zip)
           }, delayFactor * 1100);
       } else {
           console.log("Error: " + status);
       }
   });
}

希望对您有所帮助!