Wait until a condition is true?

前端 未结 7 1966
日久生厌
日久生厌 2020-12-09 08:32

I\'m using navigator.geolocation.watchPosition in JavaScript, and I want a way to deal with the possibility that the user might submit a form relying on locatio

7条回答
  •  我在风中等你
    2020-12-09 09:11

    Try using setInterval and clearInterval like this...

    var current_latlng = null;
    
    function gpsSuccess(pos) {
        //console.log('gpsSuccess');  
        if (pos.coords) {
            lat = pos.coords.latitude;
            lng = pos.coords.longitude;
        } else {
            lat = pos.latitude;
            lng = pos.longitude;
        }
        current_latlng = new google.maps.LatLng(lat, lng);
    }
    watchId = navigator.geolocation.watchPosition(gpsSuccess,
        gpsFail, {
            timeout: 5000,
            maximumAge: 300000
        });
    $('#route-form').submit(function (event) {
        // User submits form, we need their location...
        // Checks status every half-second
        var watch = setInterval(task, 500)
    
        function task() {
            if (current_latlng != null) {
                clearInterval(watch)
                watch = false
                return callback()
            } else {
                toastMessage('Waiting for your location...');
    
            }
        }
    
        function callback() {
            // Continue on with location found...
        }
    });
    

提交回复
热议问题