Adding time delay to google map geocode

与世无争的帅哥 提交于 2020-01-03 03:04:12

问题


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:


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);
    }
}


来源:https://stackoverflow.com/questions/7659187/adding-time-delay-to-google-map-geocode

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!