jquery 从另一个函数获取变量

jquery getting variable from another function

我有一个函数来获取当前地址(效果很好),它是由另一个 jquery 函数触发的,我用它来将 ajax 的结果传递给 mysql。

脚本:

var currentlocation;

function getlocation(){

        navigator.geolocation.getCurrentPosition(
            function( position ){ 

                var lat = position.coords.latitude;
                var lng = position.coords.longitude;
                var google_map_pos = new google.maps.LatLng( lat, lng );

                var google_maps_geocoder = new google.maps.Geocoder();
                google_maps_geocoder.geocode(
                    { 'latLng': google_map_pos },
                    function( results, status ) {
                        if ( status == google.maps.GeocoderStatus.OK && results[0] ) {
                            console.log( results[0].formatted_address );
                            currentlocation = results[0].formatted_address;
                            console.log('cl1: ' + currentlocation);
                        }
                    }
                );
            },
            function(){ 
            }
        );
}

//and jquery function (there are multiple functions similar to this one    using the getlocation()

$(document).ready(function () {
    $('[id^=start-]').on('click', function (e) {
        getlocation();
        console.log('cl2: ' + currentlocation);
        var locationsql = currentlocation;
        console.log('cl3:' + locationsql);
    });
});

控制台打印出 cl2 和 cl3 的未定义结果,然后稍后在 cl1 中 google 位置的正确结果。

所以我遇到的问题是获取变量 currentlocation 所以我可以稍后使用它,就像在这种情况下 locationsql

高度重视的建议

由于 geocode() 函数本身是异步的,您必须添加一个回调函数,

function( results, status ) {
                                if ( status == google.maps.GeocoderStatus.OK && results[0] ) {
                                    var currentlocationTemp = results[0].formatted_address;
                                    callback(currentlocationTemp);
                                }
}

并在回调函数中接收您的变量以进行进一步操作

function callback(location){
      currentlocation = location;
}

好吧,用 jQuery 延迟方法解决了。

我的代码:

var currentlocationTemp;

function getlocation(){

        // set dfd variable
        var dfd = $.Deferred();

        /* Chrome need SSL! */
        var is_chrome = /chrom(e|ium)/.test( navigator.userAgent.toLowerCase() );
        var is_ssl    = 'https:' == document.location.protocol;
        if( is_chrome && ! is_ssl ){
            return false;
        }
        navigator.geolocation.getCurrentPosition(
            function( position ){ // success cb
                /* Current Coordinate */
                var lat = position.coords.latitude;
                var lng = position.coords.longitude;
                var google_map_pos = new google.maps.LatLng( lat, lng );

                /* Use Geocoder to get address */
                var google_maps_geocoder = new google.maps.Geocoder();
                google_maps_geocoder.geocode(
                    { 'latLng': google_map_pos },
                    function( results, status ) {
                        if ( status == google.maps.GeocoderStatus.OK && results[0] ) {
                            console.log( results[0].formatted_address );
                            currentlocationTemp = results[0].formatted_address;
                            // resolve dfd variable                             
                            dfd.resolve();
                        }
                    }
                );

            },
            function(){ // fail cb
            }

        );
        // promise dfd variable
        return dfd.promise();
   }


$(document).ready(function () {
$('[id^=start-]').on('click', function (e) {

    function start() {
        currentlocation = currentlocationTemp;
        console.log('cl: ' + currentlocation); 
        }

    //// Que of the functions
    getlocation().then(start);  

});
});