Pregunta

I am building a HERE MAPS based web application. I'm trying to implement getting the driving directions to work from >= 2 waypoints.

So the user inputs his adresses. Firstly, the application has to geocode these addresses to avoid errors.

This is the form submit event handler:

$('.form-directions').on('submit', function () {
    waypoints = [];
    $('.waypoint').each(function () {
        geoCode($(this).val());
    });
    return false;
});

This is the geoCode() function:

function geoCode (address) {
    nokia.places.search.manager.findPlaces({
        searchTerm: address,
        onComplete: onGeoCodingCompleted,
        searchCenter: map.center
    }); 
}

This is an async task, when finished it calls onGeoCodingCompleted(), which is the following:

function onGeoCodingCompleted(data, requestStatus, requestId) {
    if (requestStatus == "OK") {   
        var locations = data.results.items;
        waypoints.push(locations[0].position);
    } else if(requestStatus == "ERROR") {
        alert("error");
    }
}

So after the geocoding process is completed, I'd like to plan the driving directions. The problem is, that I don't know if all the geocoding processes have finished. If the user submits ex. 150 addresses, it would take longer than if 2 addresses were submitted.

tl;dr How can I set up a handler that calls a function when all of the geoCode() tasks have finished?

¿Fue útil?

Solución

You can use promises.

$('.form-directions').on('submit', function () {
    var promises = [];
    waypoints = [];
    $('.waypoint').each(function () {
        promises.push(geoCode($(this).val()));
    });
    $.when.apply(null, promises).then(function() {
        // Everything is done, do something
    });
    return false;
});

And then in your geoCode function

function geoCode (address) {
    var deferred = $.Deferred();
    nokia.places.search.manager.findPlaces({
        searchTerm: address,
        onComplete: function(data, requestStatus, requestId) {
            onGeoCodingCompleted(data, requestStatus, requestId);
            deferred.resolve();
        },
        searchCenter: map.center
    });
    return deferred.promise();
}

Otros consejos

Use jquery deferred. Example code:

function do_stuff(){
    var deferred = $.Deferred();

    $.getJSON('/whatever.php/?callback=?',params,
        function(response){
            deferred.resolve(response);
        });

    });
    return deferred;
}
$.when( do_stuff() , do_stuff() ).done(function(a1, a2) {
    console.log('Stuff 1:' + a1);
    console.log('Stuff 2:' + a2);
});
Licenciado bajo: CC-BY-SA con atribución
No afiliado a StackOverflow
scroll top