Geolocation API - wait for getting position

谁说我不能喝 提交于 2019-12-25 04:15:47

问题


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?


回答1:


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


来源:https://stackoverflow.com/questions/39960719/geolocation-api-wait-for-getting-position

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!