geo = function(options){ geocoder.geocode( options,function(results,status) { if (status == google.maps.GeocoderStatus.OK) { var x = results; alert('pear'); return x; } else { return -1; } }); } getAddr = function(addr){ if(typeof addr != 'undefined' && addr != null) { var blah = geo({ address: addr,}); alert('apple'); return blah; } return -1; }
因此,当我调用getAddr时,我得到了未定义,也首先提醒苹果,然后是梨.我意识到google以异步方式映射地理编码,但有没有办法让这个工作?
解决方法
你将无法这样做.您对Google的地理编码器进行了异步调用,这意味着您无法让getAddr返回结果.相反,你应该做这样的事情:
getAddr = function(addr,f){ if(typeof addr != 'undefined' && addr != null) { geocoder.geocode( { address: addr,},status) { if (status == google.maps.GeocoderStatus.OK) { f(results); } }); } return -1; }
然后你在代码中使用:
getAddr(addr,function(res) { // blah blah,whatever you would do with // what was returned from getAddr prevIoUsly // you just use res instead // For example: alert(res); });
编辑:如果你想,你还可以添加更多状态验证:
getAddr = function(addr,status) { if (status == google.maps.GeocoderStatus.OK) { f('ok',results); } else { f('error',null); } }); } else { f('error',null); } }
你可以像这样使用它:
getAddr(addr,function(status,res) { // blah blah,whatever you would do with // what was returned from getAddr prevIoUsly // you just use res instead // For example: if (status == 'ok') { alert(res); } else { alert("Error") } });