简体   繁体   中英

Function returning undefined when value set to null

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;

    }   

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" ...
  //
});

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM