Код JavaScript, кажется, пропускает обратный вызов другой функции - PullRequest
0 голосов
/ 25 апреля 2018

Я пишу функции в моем файле JavaScript для вывода адреса.Это не самый чистый, но он работал до того, как появилась моя текущая проблема.Я пытаюсь callback и получить адрес, но когда я регистрирую адрес на console, это undefined.Я не уверен, что я делаю неправильно.

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);
            }
        }
    }
}

Это функция, которую я использую callback из:

// 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;
    }
}

1 Ответ

0 голосов
/ 25 апреля 2018

функция с обратным вызовом не блокирует выполнение, поэтому ваша функция clientLoc вызывается, и, предположительно, если этот код работает, переменная origin будет установлена, и ваш вызов оповещения сработает ... НО код ниже clientLoc неожидание завершения вызова clientLoc ... он проходит через оставшуюся часть функции ... если я не слишком знаком с синтаксисом es6, но концепция та же.Вы, вероятно, хотите переместить console.log ("мое местоположение:" + origin);и любой код, который использует переменную origin, установленную внутри обратного вызова, чтобы сделать его чище, использует некоторые обещания

Добро пожаловать на сайт PullRequest, где вы можете задавать вопросы и получать ответы от других членов сообщества.
...