Waiting for a Google Maps geocoder?

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; } 

Therefore, when I call getAddr, I get undefined, and first the apple is warned, and then the pear. I understand that google maps geocodes is asynchronous, but is there a way to make this work?

+6
source share
1 answer

You cannot do it. You have an asynchronous call to google geocoder, which means that you cannot return getAddr results. Instead, you should do something like this:

 getAddr = function(addr, f){ if(typeof addr != 'undefined' && addr != null) { geocoder.geocode( { address: addr, }, function(results, status) { if (status == google.maps.GeocoderStatus.OK) { f(results); } }); } return -1; } 

And then you use in your code:

 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); }); 

EDIT: if you want, you can also add another status confirmation:

 getAddr = function(addr, f){ if(typeof addr != 'undefined' && addr != null) { geocoder.geocode( { address: addr, }, function(results, status) { if (status == google.maps.GeocoderStatus.OK) { f('ok', results); } else { f('error', null); } }); } else { f('error', null); } } 

And you can use it like this:

 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") } }); 
+10
source

Source: https://habr.com/ru/post/908802/


All Articles