0

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.

1
  • If the API forces you to get the returned value in a callback instead of returning it from the function, don't you think there's a reason? Commented Nov 8, 2010 at 13:30

1 Answer 1

1

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.

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

3 Comments

Does this mean I need to do something else, (store in DOM or an XML file etc?)
@akd: Do you understand what's going on?
I think i do, the problem with moving it within the call back is that i need to geo-locate 3-4 locations.

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.