我只是想知道以下用例的正确 Geolocation API 用法是什么:
我有某种形式的网站(针对手机)。用户输入一些文本并按“提交”。我需要记录用户的位置(GPS 坐标)以及输入的数据,并且(重要!)如果用户未授予许可或我们无法确定他/她的位置,则会发出一些警告消息。
从我的 Angular 来看,问题在于 Geolocation API 是异步的。因此,按下“提交”后,执行流程将分离到主流程,提交后照常运行 - 将数据记录到数据库,而异步流程 - 仅当 API 接收到坐标时才执行回调。
目前我已经实现了一些解决方法 - 添加自定义 getLocation JS 函数到 onSubmit 执行:
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.");
}
}
但是这种方法将数据记录和位置记录分开,我不能禁止数据保存无位置..
当我是异步新手时,我只想拥有 GetCurrentPosition 函数的同步版本,但这似乎是不可能的\意识形态上错误的解决方案。但是这种情况我该怎么办呢?
最佳答案
在此处查看此示例:https://developer.mozilla.org/en-US/docs/Web/API/Geolocation/getCurrentPosition
基本上,如果您使用 JavaScript 执行 POST - 就没有问题。
你可以这样做:
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);
}
关于javascript - 地理定位 API - 等待获取位置,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/39960719/