简体   繁体   中英

JavaScript code seems to skip callback to another function

I am writing functions in my JavaScript file to output an address. It is not the cleanest, but it worked before my current issue came up. I am trying to callback and get an address but when I log the address to the console , it is undefined . I'm not sure what I am doing wrong.

function calculateDistance(vnames, vlocations) {
    // PROGRAM NEVER GOES THROUGH THIS???
    clientLoc((address) => {
        var origin = address;
        alert("Address: " + address);
    });
    // PROGRAM NEVER GOES THROUGH THIS???

    console.log("my location is: " + origin);

    var venueNames = vnames,
    venueLocs = vlocations,
    service = new google.maps.DistanceMatrixService();

    // 5. Output band name and distance
    // Matrix settings
    service.getDistanceMatrix(
        {
            origins: [origin],
            destinations: venueLocs,
            travelMode: google.maps.TravelMode.DRIVING, // Calculating driving distance
            unitSystem: google.maps.UnitSystem.IMPERIAL, // Calculate distance in mi, not km
            avoidHighways: false,
            avoidTolls: false
        },
        callback
    );

    // Place the values into the appropriate id tags
    function callback(response, status) {
        // console.log(response.rows[0].elements)
        // dist2 = document.getElementById("distance-result-2"),
        // dist3 = document.getElementById("distance-result-3");

        for(var i = 1; i < response.rows[0].elements.length + 1; i++) {
            var name = document.getElementById("venue-result-" + i.toString()),
            dist = document.getElementById("distance-result-" + i.toString());

            // In the case of a success, assign new values to each id
            if(status=="OK") {
                // dist1.value = response.rows[0].elements[0].distance.text;
                name.innerHTML = venueNames[i-1];
                dist.innerHTML = response.rows[0].elements[i-1].distance.text;
            } else {
                alert("Error: " + status);
            }
        }
    }
}

This is the function I am using the callback from:

// Find the location of the client
function clientLoc (callback) {
    // Initialize variables
    var lat, lng, location

    // Check for Geolocation support
    if (navigator.geolocation) {
        console.log('Geolocation is supported!');

        // Use geolocation to find the current location of the client
        navigator.geolocation.getCurrentPosition(function(position) {
            console.log(position);
            lat = position.coords.latitude;
            lng = position.coords.longitude;

            // Client location coordinates (latitude and then longitude)
            location = position.coords.latitude + ', ' + position.coords.longitude
            // console.log(location)

            // Use Axios to find the address of the coordinates
            axios.get('https://maps.googleapis.com/maps/api/geocode/json?key=AIzaSyAg3DjzKVlvSvdrpm1_SU0c4c4R017OIOg', {
                params: {
                    address: location,
                    key: 'AIzaSyBH6yQDUxoNA3eV81mTYREQkxPIWeZ83_w'
                }
            })
            .then(function(response) {
                // Log full response
                console.log(response);

                var address = response.data.results[0].formatted_address;
                // Return the address
                console.log(address);
                //return clientLoc.address;

                // CALLBACK
                callback(address);
            })
        });
    }
    else {
        console.log('Geolocation is not supported for this Browser/OS version yet.');
        return null;
    }
}

a function that has a callback doesn't block execution, so your function clientLoc gets called and presumably if that code works, the origin variable will get set and your alert call will fire ... BUT the code below clientLoc is not waiting for the clientLoc call to finish ... it proceeds through the rest of the function ... granted i'm not too familiar with the es6 syntax but the concept is the same. You probably want to move the console.log("my location is: " + origin); and any code that reiles on the origin variable being set inside the callback, to make it cleaner use some promises

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