非常奇怪的Javascript范围问题
以下变量my_cords在进入谷歌地图功能时未定义,有人能理解为什么并可能给我一个解决方法吗?我已经在顶部定义了它,并将其设置在回调函数中,我以前见过它在全局变量上的工作非常奇怪的Javascript范围问题,javascript,variables,scope,Javascript,Variables,Scope,以下变量my_cords在进入谷歌地图功能时未定义,有人能理解为什么并可能给我一个解决方法吗?我已经在顶部定义了它,并将其设置在回调函数中,我以前见过它在全局变量上的工作 $(document).ready(function () { var my_cords; var map; function getCareHome() { geocoder = new google.maps.Geocoder(); //var address = document.getEleme
$(document).ready(function () {
var my_cords;
var map;
function getCareHome() {
geocoder = new google.maps.Geocoder();
//var address = document.getElementById("address").value;
var address = "address here";
geocoder.geocode( { 'address': address}, function(results, status) {
if (status == google.maps.GeocoderStatus.OK) {
my_cords = results[0].geometry.location;
} else {
alert("Sorry we couldn't locate the carehome on the map: " + status);
return false;
}
});
var myOptions = {
zoom: 7,
center: my_cords,
mapTypeId: google.maps.MapTypeId.ROADMAP
}
map = new google.maps.Map(document.getElementById("map_canvas"), myOptions);
}
getCareHome();
});
.geocode
是一个异步调用
尝试在函数中使用回调
例如:
geocoder.geocode( { 'address': address}, function(results, status) {
if (status == google.maps.GeocoderStatus.OK) {
createMap(results[0].geometry.location);
} else {
alert("Sorry we couldn't locate the carehome on the map: " + status);
return false;
}
});
var createMap = function(my_cords) {
var myOptions = {
zoom: 7,
center: my_cords,
mapTypeId: google.maps.MapTypeId.ROADMAP
}
map = new google.maps.Map(document.getElementById("map_canvas"), myOptions);
}
geocoder.geocode是一个异步函数。设置
my_cords
的匿名函数在触发某个事件(可能是HTTP响应的到达)之前不会运行
将依赖于其运行的代码移到该函数内部。因为
geocode
是异步运行的,所以您的代码将在以后使用my\u cords
(设置myOptions
)在从geocode
运行完成回调之前,将看到my\u cords
的值,因此myOptions.center
将是未定义的
如果您在设置
myOptions
时需要my_跳线
,则必须将该代码移动到geocode
上的回调中。不建议使用var createMap=function…
表单。除此之外,+1。@Neal:function createMap
我会使用函数声明,就像OP在getCareHome
中使用的那样,而不是函数表达式。@T.J.Crowder为什么我的方式会有所不同?我只是在演示如何创建函数。我没有注意函数的OPs声明。@Neal:它发生在不同的时间,并导致一个变量引用匿名函数。函数声明发生在作用域中执行任何分步代码之前,并导致绑定和具有适当名称的函数。更多:@Neal你让这听起来很容易!谢谢你的快速回复。学到了一些新的东西。干杯,刚刚到达终点,不过我提高了你的答案!