简体   繁体   中英

How to access callbak function variable globally in jquery

In this code:

$(document).ready(function() {
        var lat = 0;
        var lng = 0;
        function getLatLng(address) {
            var geocoder = new google.maps.Geocoder();
            geocoder.geocode({'address': address}, function(results, status) {
                if (status == google.maps.GeocoderStatus.OK) {
                    lat = results[0].geometry.location.lat(); //how do I access lat 
                    lng = results[0].geometry.location.lng() //and lng outside function ormake it global
                }
            });
            alert(lat); // does not display only show's the 0
        }
        getLatLng();
    });

I want the alert(lat) to show the lat not zero.

how can I access this?

thanks in advance!

Consider using callback function when you work with asynchronous operations:

function getLatLng(address, callback) {
    var geocoder = new google.maps.Geocoder();
    geocoder.geocode({'address': address}, function (results, status) {
        if (status == google.maps.GeocoderStatus.OK) {
            lat = results[0].geometry.location.lat(); //how do I access lat 
            lng = results[0].geometry.location.lng() //and lng outside function ormake it global
            callback(lat, lng);
        }
    });
}

getLatLng(function(lat, lng) {
    alert([lat, lng]);
});

Your alert prints 0 because it is run before geocoder finishes its job. You can use callback to be notified when geocoder finishes:

$(document).ready(function() {
    var lat = 0;
    var lng = 0;
    var geocoderFinished = function(){
        alert(lat);
    };
    function getLatLng(address) {
        var geocoder = new google.maps.Geocoder();
        geocoder.geocode({'address': address}, function(results, status) {
            if (status == google.maps.GeocoderStatus.OK) {
                lat = results[0].geometry.location.lat(); //how do I access lat 
                lng = results[0].geometry.location.lng() //and lng outside function ormake it global
                geocoderFinished();
            }
        });
    }
    getLatLng();
});

It is because alert(lat); is getting executed before the success function. You should be alerting it either inside callback function or use setTimeout and give the alert.

it is bad practise to use setTimeout as we never know how long it will take to execute server side call. So its better practise to call the code in callback function to ensure the changes

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM