JavaScript从一个函数变为另一个函数

时间:2012-01-17 06:28:10

标签: javascript function variables

我遇到了从一个函数到另一个函数传递两个坐标的问题。我真的不懂JavaScript,但似乎有些正确。你能告诉我我的错误在哪里吗?

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

1 个答案:

答案 0 :(得分:2)

无法从异步函数返回值。不要试试。

改为使用回调。

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从它们返回一个值 - 它们还没有它。

一旦结果(通常是HTTP请求)准备就绪,异步函数依赖于回调函数来处理它。您必须直接或通过另一个函数调用在该回调函数中进行所有进一步处理。