Search code examples
javascripthtmlgoogle-mapsgoogle-geocodergeocode

Google Maps Geocode- dealing with the asynchronous call


I have the code:

 function mapNextAddress() {

    var xhr, i, text, lines, address;
    if(window.XMLHttpRequest)
    {
        // IE7+, Firefox, Chrome, Opera, Safari
        xhr = new XMLHttpRequest();
    }
    else
    {
        // IE5, IE6  - next line supports these dinosaurs
        xhr = new ActiveXObject("Microsoft.XMLHTTP");
    }

    xhr.onreadystatechange = function()
    {
        if(xhr.readyState == 4 && xhr.status == 200)
        {
            text = xhr.responseText;
            lines = text.split("\n"); 
            address = lines[numberAddress];
            numberAddress = numberAddress + 1;
        }
    }

    xhr.open("GET","OFCaddresses.txt",true);
    xhr.send();

    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 have a button that calls this, I am trying to update the map everytime the button is clicked to the next address in a text file. I am having some issues with the fact that it is asynchronous and that it isn't necessarily being run in this order. I am stuck trying to think of a workaround for this, any ideas?


Solution

  • Why don't you call geocode in the xhr.onreadystatechange event?

    xhr.onreadystatechange = function()
    {
        if(xhr.readyState == 4 && xhr.status == 200)
        {
            text = xhr.responseText;
            lines = text.split("\n"); 
            address = lines[numberAddress];
            numberAddress = numberAddress + 1;
    
            doGeocode();
        }
    }
    

    And the logic of doGeocode function is not modified

    function doGeocode() {
        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);
        }
    });
    

    PS: I really suggest you to do the Ajax stuffs with jQuery if feasible. Reinventing the wheel is not good most of the time. http://learn.jquery.com/ajax/