views:

343

answers:

2

I have found this code for reverse geocoding:

var point = new GLatLng (lat[1],long[1]);
var geocoder = new GClientGeocoder();
geocoder.getLocations (point, function(result) { alert (lat[1]+' '+long[1]+' '+result.address); });

But it pops the alert, saying that result.address is 'undefined'. Any ideas, what could be the problem?


EDIT: Got it working, thanks.

+1  A: 

From this I can only tell that result is not being passed to the function or it is not an object.

You need to see what parameters the callback function receives. Here's what the documentation says:

This response will contain a Status code, and if successful, one or more Placemark objects.

If you're using Firebug, you can see what's being passed to the callback this way:

var point = new GLatLng (lat[1],long[1]);
var geocoder = new GClientGeocoder();
geocoder.getLocations (point, function(result) { 
    window.console.log(arguments);
    // Here you will see what arguments are passed and
    // decide what to do about them
});
Igor Zinov'yev
+3  A: 

can you include the definitions of 'lat' and 'long'? also, 'long' is a reserved keyword, so that is likely a typo / bug.

also, the results that come back, at least in gmaps v2 json format, have a more complex structure, and 'result.address' won't have anything. when I tested it out, I needed to access one of the addresses with something like:

result.Placemark[0].address

see http://code.google.com/apis/maps/documentation/geocoding/index.html#GeocodingResponses

Karl R
Thanks, result.Placemark[0].address works!
just one more thing, if I replace 'alert' with a variable, say x = result.Placemark[6].address; , then it seems that this x isn't accessible outside the function?
yeah, anything defined within the callback will only be accessible from within that callback. it's probably best to do any work you need to do from within the callback if at all possible. A messier way might be to define an object or array outside of the function and add the result to that.
Karl R
>>> A messier way might be to define an object or array outside of the function and add the result to that. <<< tired it like that, but didn't really seem to work. just need to get that variable out of the function...var g;var geocoder = new GClientGeocoder();geocoder.getLocations ( new GLatLng (lat[1],long[1]) , function(result) { g = ( result.Placemark[1].address ); });document.write( g );
the issue there is that the call to 'document.write(g)' occurs before the callback from the reverse geocoding request returns. that's why it really is better to do what you need from within that callback, otherwise you'll have to worry about the timing of the callbacks.
Karl R
hmm... I can't really do everything I need from within that function, as I need to get a variable out to pass it into another function.