代码
class $getPositions {
constructor(arg) {
this.id = arg.id || 0;
this.fn = arg.fn ? function(data) {
arg.fn(data);
} : function(data) {
console.log("未设置输出回调")
return data;
};
this.ourPosition = [];
this.nowPosition = [];
this.onceNowPosition = [];
this.getOnceSPosition = null;
this.state = false;
this.isContinued = false;
this.isContinuedTimeInt = null;
this.isContinuedTimeOut = null;
return this;
}
init() {
return this;
}
continued() {
console.log("开始持续定位")
let that = this;
this.isContinued = true;
if (this.isContinuedTimeInt) {
console.log("重复开始持续定位")
return;
} else {
that.once(function(res) {
if (res.state == false) {
console.log(res.intlat)
}
})
this.isContinuedTimeInt = setInterval(() => {
that.once(function(res) {
if (res.state == false) {
console.log(res.intlat)
}
})
}, 5000)
}
}
continuedTime(val) {
let that = this;
if (val != 1) {
this.isContinued = true;
that.once(function(res) {
if (res.state == false) {
that.outData();
}
})
if (this.isContinuedTimeOut) {
return;
}
}
this.isContinuedTimeOut = setTimeout(() => {
that.once(function(res) {
if (res.state == false) {
that.outData();
if (res.ok) {
that.continuedTime(1);
} else {
that.continuedTime(1);
}
}
})
}, 30000)
}
overContinued() {
let that = this;
if (this.isContinued) {
this.isContinued = false;
if (this.isContinuedTimeInt) {
clearInterval(that.isContinuedTimeInt);
this.isContinuedTimeInt = null;
}
if (this.isContinuedTimeOut) {
clearTimeout(that.isContinuedTimeOut);
this.isContinuedTimeOut = null;
}
}
this.isContinued = false;
that.outData('out');
}
once(fn) {
this.state = true;
let ok = true;
let that = this,
fns = fn || '',
outit = function() {
if (fns) {
fns({
state: that.state,
intlat: that.onceNowPosition,
ok: ok
})
} else {
that.outData();
}
};
outit();
let success = function(position) {
var lat = position.coords.longitude;
var lon = position.coords.latitude;
that.onceNowPosition = [lat, lon];
that.state = false;
ok = true;
outit();
};
let error = function(error) {
let msg = "none";
switch (error.code) {
case error.PERMISSION_DENIED:
msg = "User denied the request for Geolocation.";
break;
case error.POSITION_UNAVAILABLE:
msg = "Location information is unavailable.";
break;
case error.TIMEOUT:
msg = "The request to get user location timed out.";
break;
case error.UNKNOWN_ERROR:
msg = "An unknown error occurred.";
break;
}
that.onceNowPosition = msg;
that.state = false;
ok = false;
outit();
};
let options = {
enableHighAccuracy: true,
timeout: Infinity,
maximumAge: 0,
};
this.getOnceSPosition = navigator.geolocation.getCurrentPosition(
success,
error,
options
);
}
outInit() {
}
outData(val) {
let d = {
state: this.state,
intlat: this.onceNowPosition
}
if (val) {
d[val] = val
}
this.fn(d)
}
}
export default $getPositions;
export default positions
使用
new $getPositions({
id: id,
fn: function(res) {
state.isOnTaskValue[id] = {
id: id,
intlat: res.intlat
}
$store.commit("setMsg", {
id: id,
intlat: res.intlat
})
}