I have the following JavaScript function which receives coordinates and returns the nearest tube station:
function coord() {
var metro = new YMaps.Metro.Closest(new YMaps.GeoPoint(<?=getCoords($addr) ?>), { results : 1 } )
YMaps.Events.observe(metro, metro.Events.Load, function (metro) {
if (metro.length()) {
metro.setStyle("default#greenSmallPoint");
var firstStation = metro.get(0);
var tubest = (firstStation.text).split("метро ");
var tube = tubest[1];
if($("span#tubest").text() == '') {
$('.whiteover').hide();
}
} else {
if($("span#tubest").text() == '') {
$('.whiteover').hide();
}
}
});
}
The value which I need to output as a result of this function execution is the value of the "tube" variable (var tube = tubest[1];). Basically a simple document.write will work. Or a simple return value like:
var tubestation = coord();
However I'm not sure how to achieve this.
You can't have this function return the value, since you're using an observer pattern - which sets up an asynchronous logic to the code. Simply saying, at the time that your
coord()
function returns, the value is not there yet.To deal with this, normally you would pass a callback function, then resume your computation there.
Declare your function as:
then, after you know the value you want, call the callback with the value:
Do it after your
if { ... } else { ... }
so your callback gets called both on success and on failure (on failure it will passundefined
, you might want to correct it by declaringvar tube = null
before theif
).then, instead of:
call it like this:
You probably won't be able to use
document.write
since the time to use it would be long past, but you can set the value as the contents of an element that you already generated. You have jQuery in your tags, so it's quite easy:assuming you have
<div id="tube_station"/>
somewhere in your HTML.