Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Items added to a global array variable do not persist outside of the adding function

I'm trying to use the Google maps JavaScript API to draw a line between two points. The two points need to be geocoded (transformed into google.maps.LatLong objects) before they can be used to draw a line.

The Geocoding function is codeAddress, and when it returns it calls the callback function that adds the new latlong to a global array called points. For some reason the values added to points do not persist outside of the array. I'm relatively new to JavaScript so I can't tell what might be wrong, any thoughts would be appreciated!

var points = new Array();

function addGeocodedLatLongToGlobalList(address) {
        points.push(address);
        alert("added a point " + points[0]); // correctly outputs latlong object
    }

function codeAddress(address) {
    geocoder = new google.maps.Geocoder();
    geocoder.geocode({ 'address': address, }, function (results, status) {
        if (status == google.maps.GeocoderStatus.OK) {
            addGeocodedLatLongToGlobalList(results[0].geometry.location);
        } else {
            alert("Geocode was not successful for the following reason: " + status);
        }
    });
}

function drawLine(address1, address2, color) {

    codeAddress(address1);
    codeAddress(address2);

    alert("there is a point " + points[0]);  //now the points[0] value is undefined
    ...
like image 665
Kate R Avatar asked Apr 09 '26 09:04

Kate R


1 Answers

I'm guessing that you're looking into the points array before the asychronous geocode function has completed and the points have actually been put into the array.

The geocoder.geocode() function is probably an asynchronous function and your calls to the codeAddress function only initiate that process and it completes some time later. That would explain why the alert() in your drawLine() function doesn't see any points - they aren't there yet. They will be put into the points array when the geoCode function actually completes and calls it's callback.

like image 107
jfriend00 Avatar answered Apr 11 '26 00:04

jfriend00