akd5446
akd5446

Reputation: 109

Java script callback modify variables - Google api geocode

Im using Google's geocode/googlemaps api. I can succesfully geo-code a location, and place a marker, however im having trouble putting the lat/long in a varible outside the call back function

function init() {
var latLng = new Array();//Setup the cities lat + long in array

this.foo = 3;

function addGeo(me){//call back function
    me.foo = 2;
return function (results, code){
  var marker = new google.maps.Marker({
        map: map, 
        position: results[0].geometry.location
      });

  me.foo = 7;
  this.foo = 8;
    }
}

var geo = new google.maps.Geocoder();
geo.geocode( {address: 'London', region: 'UK'}, addGeo(this));


var map = new google.maps.Map(document.getElementById("full_map"));

var latLngBounds = new google.maps.LatLngBounds( );

//For each city, add its location to the boundry and add a marker in that location
for ( var i = 0; i < latLng.length; i++ ) {
    latLngBounds.extend( latLng[ i ] );

}

alert(this.foo);

map.setCenter(latLngBounds.getCenter( ));
map.fitBounds(latLngBounds);
map.setMapTypeId(google.maps.MapTypeId.TERRAIN);

}

Thats my full code, I can get addGeo (the callback function) to edit the foo varible, but not within the returned function, this will alert 2 (value of this.foo), I to do this to store the lat and long in latLong array so I can make use of googles latLngBounds.

Any help will be greatly appreciated.

EDIT:

For anyone intrested i put me.latLngBounds.extend(results[0].geometry.location); me.map.fitBounds(latLngBounds); (after setting the relevent varibles in the main section) within the unamed function, and it works like a treat.

Upvotes: 0

Views: 875

Answers (1)

SLaks
SLaks

Reputation: 887365

The geocode method is asynchronous (the A in AJAX), meaning that it will return immediately, without waiting for a reply from the server.

Therefore, the geocode callback only executes after the rest of your code (when the server replies).
Your alert(this.foo) runs before you receive a reply, before foo is set.

You need to move all of the code that uses the response into the callback.

Upvotes: 1

Related Questions