2014-03-01 57 views
0

所以,我有这段代码:如何从JavaScript中的内部函数为外部变量赋值?

function centermap(){ 
    var geocoder = new google.maps.Geocoder(); 
    var address = document.getElementById('office_address').value; 
    var new_location = ""; 
    geocoder.geocode({'address': address}, function(results, status, new_location) { 
    if (status == google.maps.GeocoderStatus.OK) { 
     new_location = results[0].geometry.location; 
     console.log(new_location); // output is fine here 
    } 
    else { 
     console.log("Geocode was not successful for the following reason: " + status); 
    } 
    }) 
    console.log(new_location); // output is "" - which is the init value 
    return new_location // the returned object is also "" 
}; 

$("input[id=office_address]").change(function(){ 
    var coordinates = new Array(); 
    var location = centermap(); 
    coordinates.push(location.geometry.location.lat()); 
    coordinates.push(location.geometry.location.lng()); 
    map.setView(coordinates, 14); 
}); 

什么我没有得到有关这里的范围?如何将“外部”new_location设置为地址结果? 请随意点上这个

编辑对我的理解所有的错误:我看过的答案上thisthis这样的问题,但我没能做到我想要的。

+0

这里最重要的一点是,'geocoder.geocode'是异步的。 –

回答

1

正如有人在评论中指出的那样,geocode函数是异步的,所以一旦它被执行,它将不会返回任何值。 考虑这个工作流程:

... 
geocoder.geocode(...); 
// this is executed straight after you call geocode 
console.log(new_location); 

... 
... 
// probably at a certain point here your geocode callback is executed 
function(results, status, new_location) { 
    if (status == google.maps.GeocoderStatus.OK) { 
    ... 
}); 

重要的是一个回调函数传递给您的centermap还有:

$("input[id=office_address]").change(function(){ 
    var coordinates = new Array(); 
    // pass a callback to execute when geocode get the results 
    centermap(function (location){ 
    coordinates.push(location.geometry.location.lat()); 
    coordinates.push(location.geometry.location.lng()); 
    map.setView(coordinates, 14); 
    }); 
}); 

function centermap(callback){ 
    var geocoder = new google.maps.Geocoder(); 
    var address = document.getElementById('office_address').value; 
    geocoder.geocode({'address': address}, function(results, status) { 
    var new_location = ''; 
    if (status == google.maps.GeocoderStatus.OK) { 
     new_location = results[0].geometry.location; 
     console.log(new_location); // output is fine here 
    } 
    else { 
     console.log("Geocode was not successful for the following reason: " + status); 
    } 
    // at this point we return with the callback 
    callback(new_location); 
}); 
// everything here is executed before geocode get its results... 
// so unless you have to do this UNRELATED to geocode, don't write code here 
}; 
+0

非常感谢@MarcoCI,你指出我正确的方向,现在我的单张地图“监听”我的地址文本字段(它具有谷歌地方的自动完成功能)的变化。一旦我完成了整个项目,我将写一篇简短的教程。 :) – sebkkom

相关问题