我需要在单击ajax按钮时获取访问者的位置,然后才将表单数据发送给操作。
到目前为止,我已经能够根据课程的存在情况有条件地提交。
问题是我的代码中的navigator.geolocation条件没有得到解析,尽管用户显示了同意弹出窗口并单击了OK。 它只是跳过此步骤并显示后备位置。
这是我更改的默认帆ajax-button组件:
methods: {
click: async function () {
let btnDelayed = document.getElementById('btn-search');
if (btnDelayed && btnDelayed.classList.contains('delayed')) {
console.log('btn-search cannot emit click');
await this.loadGeoData();
} else {
console.log('btn-search can emit click ');
this.$emit('click');
}
},
loadGeoData: async function () {
let loc = await this.getLocation();
console.log('location');
console.dir(loc);
/*
let test = {
lat: 0.22,
lng: 0.55
};
*/
let btnSubmit = document.getElementById('btn-search');
btnSubmit.classList.remove('delayed');
let pos = JSON.stringify(loc);
this.$emit('pos', pos);
console.log('pos event value ' + pos);
this.click();
},
getLocation: async function () {
let loc = {
lat: 0,
lng: 0
};
if (navigator.geolocation) {
let options = {
enableHighAccuracy: true,
timeout: 10000,
maximumAge: 0
};
console.log('geolocation loaded');
navigator.geolocation.getCurrentPosition(function (position) {
console.log('getting position...');
console.dir(position);
loc.lat = position.coords.latitude;
loc.lng = position.coords.longitude;
}, (err) => {
console.warn(`ERROR(${err.code}): ${err.message}`);
}, options);
}
return loc;
}
}
这是控制台日志输出:
btn-search cannot emit click
geolocation loaded
location
{…}
lat: 0
lng: 0
<prototype>: Object { … }
pos event value {"lat":0,"lng":0}
btn-search can emit click
// getting the data in the instance
argins
{…}
__ob__: Object { value: {…}, dep: {…}, vmCount: 0 }
actionref: "{\"lat\":0,\"lng\":0}"
actiontype: "word"
search:
尽管执行了avigator.geolocation.getCurrentPosition,但是提交了表单,
getting position... ajax-button.component.js:108:13
Position
coords: Coordinates { latitude: 44.00000000000, longitude: 26.00000000000, accuracy: 931, … }
timestamp: 1548163982134
_
当然,我需要先执行它。
答案 0 :(得分:0)
对于其他读者,
经过几天的搜索,我发现了这篇帖子Catch Geolocation Error - Async Await,解释了如何通过异步/等待来实现地理定位。
其余的只是修改ajax-button组件的click事件。