Search code examples
javascriptjquerygeolocationjquery-callback

Delay form submission until location is retrieved


I have an application that attempts to get locations settings from the browser, this tends to take a little while so I want it to run when the page loads. However, if you click the submit button before the location callback has run, you have no location data. My question is simple, how do I wait for my location success callback to finish before submitting my form? (without something silly like a sleep statement).
Ideally I'd like to flash a busy indicator and wait for the data. Is this possible? I have the code to make a busy indicator visible, but am not sure how I can elegantly wait for the data to be available.

$(document).ready(function(){
    var lat = "";
    var lng = "";
    var accuracy = "";
    var locationFound = false;

    if(navigator.geolocation){
        navigator.geolocation.getCurrentPosition(function positionSuccess(loc){
            lat = loc.coords.latitude;
            lng = loc.coords.longitude;
            accuracy = loc.coords.accuracy;
            locationFound = true;               
        });
    }else{
        alert("I'm sorry, your jerk browser doesn't support geolocation");
        locationFound = true;
    }

$('#locForm').submit(function(e){  

        $('#lat').val(lat);
        $('#lng').val(lng);
        $('#boundary').val($('#boundary-select').val());
}

Solution

  • Disable the submit button until the location data has been passed.

    $('input[type="submit"]').attr('disabled','disabled');
    

    Then enable the submit button

    $('input[type="submit"]').removeAttr('disabled');