Geocoding with Google Maps without OVER_QUERY_LIMIT errors

Problem: A JavaScript application needs to do more geocoding lookups than Google will let you do at once. It’s possible to use setTimeout() to make JavaScript wait, but with the callbacks, it’s cumbersome.

Solution: Use a server-side script that will retrieve the same data, requesting it over and over if an OVER_QUERY_LIMIT error occurs.

PHP:

$params = "address=" . urlencode($_GET{'addr'});
$url = 'http://maps.googleapis.com/maps/api/geocode/json?sensor=false&' . $params;
$json = file_get_contents($url);
$status = json_decode($json)->status;

// check for over_query_limit status
while ($status=="OVER_QUERY_LIMIT") {
    sleep(0.2); // seconds
    $json = file_get_contents($url);
    $status = json_decode($json)->status;
}

header('application/json');
echo $json;

JavaScript: replace this line:

geocoder.geocode( {'address': address}, function(results, status) {

with this:

var url_addr = encodeURIComponent(address);
$.getJSON('geocode.php?addr='+url_addr, function(data) { 
    var results = data.results,
        status = data.status;

4 Replies to “Geocoding with Google Maps without OVER_QUERY_LIMIT errors”

  1. You solved the problem! My first attempt was with javascript setTimeout but I didn’t get good results. Thanks to your script, everything now works fine. Thank you very much!!!!

  2. Hi,

    after entering

    var url_addr = encodeURIComponent(address);
    $.getJSON(‘geocode.php?addr=’+url_addr, function(data) {
    var results = data.results,
    status = data.status;

    instead

    geocoder.geocode( {‘address’: address}, function(results, status) {

    in my JS-File I want to call the following:

    if (status == google.maps.GeocoderStatus.OK) {
    if (results[1]) {
    console.log (“Everything OK”);
    }

    But it doesn´t work. In the Console I see that the php-file becomes called and the calculated geocode becomes attached, but it seems it doesn´t find the way to my google.maps.GeocoderStatus.OK-Loop above.

    Do you have any idea what could be wrong?

    I hope you can help.

    Thank you and regards from Germany,

    Stefan

  3. @Stefan Maier. It is because you are using AJAX. And before you got the output from php file, “if (status == google.maps.GeocoderStatus.OK) {” statement is executed and can’t get OK status.

Leave a Reply

Your email address will not be published. Required fields are marked *

*