JavaScript从一个函数变为另一个函数 [英] JavaScript getting variable from one function to another
问题描述
我遇到了从一个函数向另一个函数传递两个坐标的问题。我不太了解JavaScript,但似乎有些不正确。您可以让我知道我的错误在哪里吗?
I am having issues passing two coordinates from one function to another. I don't really know JavaScript, but it seems to be somewhat correct. Could you please let me know where is my error?
<script type="text/javascript">
function initialize() {
var address = "Chicago IL";
locs= getLatLong(address);
alert(locs.lat()); //does not work
var myOptions = {
zoom: 4,
center: new google.maps.LatLng(41, -87),
mapTypeId: google.maps.MapTypeId.ROADMAP
};
var map = new google.maps.Map(document.getElementById('map_canvas'),
myOptions);
}
function getLatLong(address){
var geo = new google.maps.Geocoder;
geo.geocode({'address':address},function(results, status){
if (status == google.maps.GeocoderStatus.OK) {
locations[0] = results[0].geometry.location.lat();
locations[1] = results[0].geometry.location.lng();
//alert(locations[0]); //test is good- works! Need to pass it back to function
//alert(locations[1]); //test is good- works! Need to pass it back to function
locs =results[0].geometry.location;
return locs;
} else {
alert("Geocode was not successful for the following reason: " + status);
}
});
}
</script>
推荐答案
不可能从异步功能。
使用回调代替。
Use a callback instead.
function setLocationOnMap(locs) {
alert(locs.lat()); // works now!
var myOptions = {
zoom: 4,
center: new google.maps.LatLng(41, -87),
mapTypeId: google.maps.MapTypeId.ROADMAP
};
var map = new google.maps.Map(document.getElementById('map_canvas'), myOptions);
}
function initialize() {
var address = "Chicago IL";
getLatLong(address, setLocationOnMap);
}
function getLatLong(address, callback){
var geo = new google.maps.Geocoder;
geo.geocode({'address':address},function(results, status){
if (status == google.maps.GeocoderStatus.OK) {
// processing...
locs = results[0].geometry.location;
callback(locs);
} else {
alert("Geocode was not successful for the following reason: " + status);
}
});
}
您必须明白异步函数调用像 geo。 geocode()
立即返回,即在任何结果准备好之前。这就是为什么你不能使用 return
从它们返回一个值 - 他们还没有。
You must understand that asynchronous function calls like geo.geocode()
return immediately, i.e. before any result is ready. That's why you can't use return
to return a value from them - they don't have it yet.
一旦结果(通常是一个HTTP请求)准备就绪,异步函数就依靠回调函数来处理它。您必须在该回调函数中直接或通过另一个函数调用来完成所有进一步处理。
Once the result (most often, an HTTP request) is ready, the asynchronous function relies on a callback function to handle it. You must do all your further processing in that callback function, either directly or by making another function call.
这篇关于JavaScript从一个函数变为另一个函数的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!