2

I have managed to geocode upto 10 address and add a marker to the map but I need to access the geocode results outside of the geocode (codeAddress) function. I thought I could push the results to a global variable array (userLat, userLng). Using alerts I can see that the loop does indeed add the results to the array within the function but the array is valueless outside of the function.

On a side note, the alert for unsuccessful geocoding should return Address 'i' depending which address had the problem but only displays the last address value of the loop.

Maybe the problems are related? I think it may have something to do with my lack of understanding of the nested function.

I hope this is clear. Thanks in advance for any help!

   function codeAddress() {

    var useradd = [];
    var geocoder = new google.maps.Geocoder();
    var howmany = parseFloat(document.getElementById("howmany").value);

    for (var i=0; i<howmany; i++) {
        useradd[i] = document.getElementById('address['+i+']').value;
        geocoder.geocode( {address: useradd[i]}, function(results, status) {
        if (status == google.maps.GeocoderStatus.OK) {
                userLat.push(parseFloat(results[0].geometry.location.lat()));
                userLng.push(parseFloat(results[0].geometry.location.lng()));
                var marker = new google.maps.Marker({
                    map: map,
                    position: results[0].geometry.location
                });
            } 
            else {
                alert('Address ' + i + ' was not successfully located for the following reason: ' + status);
            }
        });
    };
}

Edit:

I'm not sure if I understood correctly but have extracted the callback function and created a new function of it that is called by the geocoder. The problem is still the same though and the variables userLat and userLng are not carried outside of the loop. Any suggestions?

function codeAddress() {

function callBack() {
    return function(results, status){
        if (status == google.maps.GeocoderStatus.OK) {
        userLat.push(parseFloat(results[0].geometry.location.lat()));
        userLng.push(parseFloat(results[0].geometry.location.lng()));
                var marker = new google.maps.Marker({
                    map: map,
                    position: results[0].geometry.location
                });
        } 
        else {
            alert('Address ' + i + ' was not successfully located for the following reason: ' + status);
        }
    }
}    

    var userLat = [];
            var userLng = [];
    var useradd = [];
    var geocoder = new google.maps.Geocoder();
    var howmany = parseFloat(document.getElementById("howmany").value);

    for (var i=0; i<howmany; i++) {
        useradd[i] = document.getElementById('address['+i+']').value;
        geocoder.geocode({address: useradd[i]}, callBack());
    };
}

2 Answers 2

0

When your codeAddress function returns, geocoder.geocode is still doing its job, which is asynchronous. When geocoder.geocode is done, it will invoke its callback, which you're passing as an anonymous function.

The solution I suggest is to make the callback function a parameter of codeAddress, and do whatever you need from that callback (or from other function called inside the callback), instead of using the global variables approach.

Sign up to request clarification or add additional context in comments.

8 Comments

Great, thanks for this explanation. I am relatively new to javascript and very new to geocoding so not sure I entirely understand it. I will give it a go though and report how it goes.
I have altered the code how I think you are suggesting. I appologise if this is not what you were suggesting but am still trying to get my head around a lot it. Any further input would be gratefully received.
Did your updated code work? It looks fine. (ignore my previous comment, which I deleted; it was wrong)
... unless you want to use userLat and userLng right after that for loop. You can't do that, you have to use them inside the callback.
Can you suggest a method for me to have access to the geocoded results outside of the function?
|
0

It's all about scope in Javascript. If you want to access variables outside of the function, you must declare and create variables outside of the function scope and then update them.

Variables declared outside of the function scope will be available anywhere else within the script.

 var def = "bombshell";
 function changer(){
     def = "changed value";
 }
 changer();
 alert(def);

See it here - http://jsfiddle.net/daveheward/kWn8b/

3 Comments

Thanks for the quick response. The variables that I am trying to add to are already declared outside the function but for some reason it just still won't add - am I missing something?
Have you defined those variables as arrays?
Yes. First couple of lines in the script read: var userLat = []; var userLng = [];

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.