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开发者_JS百科 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" ...
//
});
精彩评论