【发布时间】:2016-10-10 14:34:33
【问题描述】:
我只是想知道以下用例的正确 Geolocation API 用法是什么:
我有某种形式的网站(针对手机)。用户输入一些文本并按“提交”。我需要记录用户的位置(GPS 坐标)以及输入的数据,并且(重要!)如果用户没有给予许可或我们无法确定他\她的位置,则会发出一些警告消息。
在我看来,问题在于 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 函数,但这似乎是不可能的\意识形态错误的解决方案。但是在这种情况下我该怎么办呢?
【问题讨论】:
标签: javascript yii geolocation