okainov
okainov

Reputation: 4654

Geolocation API - wait for getting position

I just wonder what is the correct Geolocation API usage for the following use case:

I have website (targeted to mobile phones) with some form. User enters some text and press "Submit". I need to record user's location (GPS coordinates) together with the entered data and (important!) raise some warning message if user didn't give permission or we were unable to determine his\her position.

From my point of view the problem is that Geolocation API is asynchronyous. So after pressing "Submit" execution flow separates to the main flow acting as usual after submitting - record the data to the database, and async flow - callback is only being executed when API receives coordinates.

For the moment I've implemented some workaround - added custom getLocation JS function to onSubmit execution:

function recordPosition(position) {
    var latitude = position.coords.latitude;
    var longitude = position.coords.longitude;
    //perform POST query to the server to write coordinates to the database
  }
  function getLocation() {
    if (navigator.geolocation) {
      navigator.geolocation.getCurrentPosition(recordPosition);

    } else {
      alert("Geolocation is not supported by this browser.");
    }
  }

But this approach separates data recording and position recording and I cannot forbid data save w\o position..

As soon as I'm newbie in async, I would like just to have synchonious version of GetCurrentPosition function, but it seems to be imposible\ideologically wrong solution. But what should I do in this case then?

Upvotes: 0

Views: 3755

Answers (1)

Michael Coxon
Michael Coxon

Reputation: 5510

Check out this example here: https://developer.mozilla.org/en-US/docs/Web/API/Geolocation/getCurrentPosition

Basically if you are performing your POST using JavaScript - you have no problems.

You can do something like:

HTML:

JS:

function onSubmit(){
    var iLat = document.getElementById('latitude');
    if(!iLat.value){
        getLocation();
        return false;
    }
}

function recordPosition(position) {
    var iLat = document.getElementById('latitude');
    var iLong = document.getElementById('longitude');
    iLat.value = position.coords.latitude;
    iLong.value = position.coords.longitude;

    iLat.form.submit();
}

function getLocation() {
    if (navigator.geolocation) {
        navigator.geolocation.getCurrentPosition(getLocation_success, getLocation_error);
    } else {
        alert("Geolocation is not supported by this browser.");
    }
}

function getLocation_success(pos){
    showPosition(pos);
    recordPosition(pos);
}

function getLocation_error(err){
    console.warn('ERROR(' + err.code + '): ' + err.message);
}

Upvotes: 3

Related Questions