0

I have got a function that returns the coordinates of a valid address but im having some difficulties is its an inavlid address. I was hoping to get a null value for pos1,which I set in the function if geocode fails to find a valid address.But I'm getting undefined,I know Im doing something really stupid but just cant figure what it is.

function fnCalculate(){

var pos1=getCordinates(document.getElementById("address1").value));

alert(pos1);

}

function getCordinates(address){

    var loc;    

    if(address){
        geocoder.geocode({ 'address': address}, function(results, status) {
            if (status == google.maps.GeocoderStatus.OK) {
                loc=results[0].geometry.location;
             } 
        else {
                loc=null;
            }

        });
    }

    return loc;

    }   
manraj82
  • 5,929
  • 24
  • 56
  • 83

1 Answers1

2

Your problem is that the callback function from the geocoder will not run until long after that "getCoordinates()" has returned. The structure of the code you've written simply will not work. Instead of expecting "getCoordinates()" to return something, you need to write it so that you pass in another function to be called when the location is available.

Something like:

function getCoordinates(address, callback) {

  if(address){
    geocoder.geocode({ 'address': address}, function(results, status) {
        if (status == google.maps.GeocoderStatus.OK) {
            callback( results[0].geometry.location );
        } 
        else {
            callback( null );
        }

    });
  }
}

Then, when you call your function, you pass in another function that handles the result:

getCoordinates(document.getElementById("address").value, function( loc ) {
  //
  // ... do something with "loc" ...
  //
});
Pointy
  • 405,095
  • 59
  • 585
  • 614
  • 1
    [Generic ajax is asynchronous link](http://stackoverflow.com/questions/6009206/what-is-ajax-and-how-does-it-work) – Raynos Jun 07 '11 at 12:45
  • thank you for your answer,is it possible to return that result to a variable? – manraj82 Jun 07 '11 at 13:14
  • No, not really. The callback function is called by that ".geocode()" method, or indirectly from its XHR callback, so it will not pay attention to your return value (unless it does so for its own purposes). The asynchronous environment requires that you think about the control flow through your code in a very different way than you do when writing ordinary procedural code. – Pointy Jun 07 '11 at 13:18