Geocoding happens asynchronously meaning that the rest of your code doesn't stop and wait while the geocoding happens. Geocoding also requires sending data to Google servers and waiting for the response. The callback function executing later is to be expected.
Chad Killingsworth On May 20, 6:27 am, "Miguel.camba" <[email protected]> wrote: > Hi. > > I'm using the V3 API and i'm getting an strange behavior while > geolocating. > I'm writing a function that gets an array of positions and it returns > an array of geocoded addresses properly formatted. > Here is the code: > > function getAddresses(positions){ > var geocoder = new google.maps.Geocoder(); > var addresses = []; > for (var i=0;i<positions.length;i++){ > geocoder.geocode({'latLng':positions[i]}, > function(results,status){ > if (status =='OK' && results.length > 0){ > alert('Address: "+results[0].formatted_address); > addresses[i]=results[0].formatted_address } > } ) > } > alert('just before return'); > return addresses; > } > > Here is the point. Maybe I don't understand how callbacks functions > work on JS, but the 'just before return' alert pops up first, and the > alert with the formatted address jumps after the function ended and > addresses was already returned as an empty array. > Anyone can explain this? > > Sorry about any error on my english. > > -- > You received this message because you are subscribed to the Google Groups > "Google Maps JavaScript API v3" group. > To post to this group, send email to [email protected]. > To unsubscribe from this group, send email to > [email protected]. > For more options, visit this group > athttp://groups.google.com/group/google-maps-js-api-v3?hl=en. -- You received this message because you are subscribed to the Google Groups "Google Maps JavaScript API v3" group. To post to this group, send email to [email protected]. To unsubscribe from this group, send email to [email protected]. For more options, visit this group at http://groups.google.com/group/google-maps-js-api-v3?hl=en.
