Adding time delay to google map geocode

2019-06-03 15:34发布

I'm working on this map and trying to geocode around 150 markers but I'm hitting the geocode limit. How can I add a time delay to avoid hitting the limit?

1条回答
别忘想泡老子
2楼-- · 2019-06-03 16:16

This adds a timer to the geocoding so each marker has a delay.

// Adding a LatLng object for each city 
function geocodeAddress(i) {
     geocoder.geocode( {'address': address[i]}, function(results, status) {
        if (status == google.maps.GeocoderStatus.OK) {
            places[i] = results[0].geometry.location;

            // Adding the markers 
            var marker = new google.maps.Marker({position: places[i], map: map});
            markers.push(marker);
            mc.addMarker(marker);

            // Creating the event listener. It now has access to the values of i and marker as they were during its creation
            google.maps.event.addListener(marker, 'click', function() {
                // Check to see if we already have an InfoWindow
                if (!infowindow) {
                    infowindow = new google.maps.InfoWindow();
                }

                // Setting the content of the InfoWindow
                infowindow.setContent(popup_content[i]);

                // Tying the InfoWindow to the marker 
                infowindow.open(map, marker);
            });

            // Extending the bounds object with each LatLng 
            bounds.extend(places[i]); 

            // Adjusting the map to new bounding box 
            map.fitBounds(bounds) 
        } else { 
            alert("Geocode was not successful for the following reason: " + status); 
        }
    })
}

function geocode() {
    if (geoIndex < address.length) {
        geocodeAddress(geoIndex);
        ++geoIndex;
    }
    else {
        clearInterval(geoTimer);
    }
}
var geoIndex = 0;
var geoTimer = setInterval(geocode, 200);  // 200 milliseconds (to try out)

var markerCluster = new MarkerClusterer(map, markers); 
} 
})
(); 
</script> 

ADDED. The above program can be tuned.

(1) The time interval can be reduced:

var geoTimer = setInterval(geocode, 100);  // do requests each 100 milliseconds 

(2) The function geocode() could perform several requests at each time interval, e.g. 5 requests:

function geocode() {
    for (var k = 0; k < 5 && geoIndex < address.length; ++k) {
        geocodeAddress(geoIndex);
        ++geoIndex;
    }
    if (geoIndex >= address.length) {
        clearInterval(geoTimer);
    }
}
查看更多
登录 后发表回答