Я запускаю приложение Cordova через Visual Studio. Он использует плагин геолокации для определения скорости, положения и т. Д. c. Я пытаюсь использовать прослушиватель «deviceready», чтобы начать наблюдение за положением пользователя, как только устройство будет готово. Вот мой код, чтобы получить представление о моей структуре:
import { Component } from '@angular/core';
import { PickerController } from '@ionic/angular';
import { PickerOptions } from '@ionic/core';
import { Geolocation } from '@ionic-native/geolocation/ngx';
@Component({
selector: 'app-home',
templateUrl: 'home.page.html',
styleUrls: ['home.page.scss'],
})
export class HomePage {
framework = 'At exact boarding time';
constructor(private pickerCtrl:PickerController,
private geolocation: Geolocation) {}
async showPicker() {
let opts: PickerOptions ={
buttons: [
{
text:'Done'
}
],
columns: [
{
name: 'framework',
options: [
{text:'10 minutes before boarding time',value:0},
{text:'5 minutes before boarding time',value:1},
{text:'At exact boarding time',value:2},
{text:'5 minutes after boarding time',value:3},
{text:'10 minutes after boarding time',value:4}
],
selectedIndex: 2,
}
]
}
let picker = await this.pickerCtrl.create(opts);
picker.present();
picker.onDidDismiss().then(async data=>{
let col = await picker.getColumn('framework');
this.framework=col.options[col.selectedIndex].text
})
}
}
function formatDate(date: Date) {
if(date.getSeconds()-10 < 0){
return `${date.getHours()}:${date.getMinutes()}:0${date.getSeconds()}`;
}
else{
return `${date.getHours()}:${date.getMinutes()}:${date.getSeconds()}`;
}
}
//tiny arrow function to return sum of an array, for convenience
const add = (a: any, b: any) =>
a + b
function average_walking_speed():any {
var options = {
maximumAge: 1000,
timeout: 5000,
enableHighAccuracy : true,
};
let watch = navigator.geolocation.watchPosition(onSuccess, onError, options);
let validity_counter = 0; //total tally of consecutive true values for validity
let avg_speed = 0.0; //average speed, changes with each iteration(every second)
const avg_speeds_to_be_stored = 3;
const margin_of_error = 0.3;
let avg_speeds_stored = []; //compilation of users avg_speed that meet our criteria
let speed_tracker_full = []; //compilation of the above data into one array, as well as number of consecutive valid avg_speed (validity_counter)
let speed_tracker_optimized = []; //speed_tracker_full relevant values only (validity == true)
document.getElementById("updater").innerHTML = " buffering..."
function onSuccess(position: { timestamp: string | number | Date; coords: { speed: any; }; }) {
let time = formatDate(new Date(position.timestamp)); //time speed was found
let speed = position.coords.speed; //speed found, updates every second
let validity = false; //whether speed meets our requirements or not
console.log(time,speed)
//speed is valid if it falls within this interval
if (speed >= 0.5 && speed <= 2.5){
validity = true;
validity_counter += 1;
}
else{
validity = false;
validity_counter = 0;
}
//appending each iteration into a final array
speed_tracker_full.push([time,speed,validity,validity_counter]);
//occurs if 10 valid avg_speed in a row, and num avg_speeds not yet stored
if(validity_counter == 10 && avg_speeds_stored.length + 1 <= avg_speeds_to_be_stored){
validity_counter = 0;
speed_tracker_optimized = speed_tracker_full.slice(-10) //takes previous 10 rows(which are proven to be valid)
//iterating through 10 valid avg_speed to accummulate them
for (let i = 0; i < speed_tracker_optimized.length; i++) {
avg_speed = avg_speed + speed_tracker_optimized[i][1];
}
avg_speed = avg_speed / 10; //finding mean using above accumulation
//iterating through again to confirm avg_speed is "kosher" (within margin_of_error far each avg_speed)
for (let i = 0; i < speed_tracker_optimized.length; i++){
if(Math.abs(speed_tracker_optimized[i][1]-avg_speed)/avg_speed <= margin_of_error){
continue
}
else{
avg_speed = 0; //for sake of identifying the prior conditional if false
break
}
}
//if we found a kosher avg_speed above, this stores that value in last row of the 10 rows
//of speed_tracker_optimized in question
if(avg_speed != 0){
speed_tracker_optimized[speed_tracker_optimized.length-1].push(avg_speed)
avg_speeds_stored.push(avg_speed);
}
}
//if we have stored enough values in avg_speeds_stored
if(avg_speeds_stored.length == avg_speeds_to_be_stored){
avg_speed = avg_speeds_stored.reduce(add)/avg_speeds_to_be_stored;
//check to make sure this final average speed is "kosher", storing it at the end of avg_speeds_stored if true.
for (let i = 0; i < avg_speeds_to_be_stored; i++){
if(Math.abs(avg_speeds_stored[i]-avg_speed)/avg_speed <= margin_of_error){
avg_speeds_stored.push(avg_speeds_stored[i]);
continue
}
}
//slicing avg_speeds_stored, to find the elements that were appended to the end.
avg_speeds_stored = avg_speeds_stored.slice(avg_speeds_to_be_stored)
//if the above slice has a length of what we expect, then all values were kosher, average speed found.
if(avg_speeds_stored.length == avg_speeds_to_be_stored){
navigator.geolocation.clearWatch(watch); //no longer watching location of user.
document.getElementById("updater").innerHTML = ` ` + avg_speed.toFixed(2) + ' m/s' //round to 2 decimals.
this.avg_speed = avg_speed;
}
}
}
//incase an error arises with .watchposition().
function onError(_error: any) {
document.getElementById("checker").innerHTML = " error"
}
}
document.addEventListener('deviceready', average_walking_speed(),false);
Вот мой html, чтобы увидеть, как я все загружаю. Вероятно, это будет очень простая проблема:
<ion-app>
<ion-content [fullscreen]="true">
<div id="header">
<strong>Boarding Time</strong>
<p>5:05 p.m.</p>
</div>
<div id="flight-info">
<p>Flight: numbers | Gate: num | Departure: num </p>
</div>
<div id="container">
<h1>Go-To-Gate Reminder</h1>
<div class="row">
<ion-icon size="large" name="walk"></ion-icon>
<p> Walking speed: </p>
<p id="updater">"</p>
</div>
<div class="row">
<ion-icon size="large" name="time"></ion-icon>
<p> Time to gate </p>
<p> 4 min </p>
</div>
<div class="row">
<ion-button expand="full" fill="clear" (click)="showPicker()">
<ion-icon size="large" name="triangle"></ion-icon>
<p> Send alert to reach gate: </p>
<ion-icon size="small" name="caret-down-circle"></ion-icon>
</ion-button>
</div>
<p><strong> Alert: {{framework}} </strong></p>
<p id ="checker"><strong></strong></p>
</div>
</ion-content>
</ion-app>
отредактируйте, если это поможет:
C:\Users\Josh\Documents\GoWith>cordova -v
9.0.0 (cordova-lib@9.0.1)
C:\Users\Josh\Documents\GoWith>cordova plugins
cordova-plugin-add-swift-support 2.0.2 "AddSwiftSupport"
cordova-plugin-device 2.0.2 "Device"
cordova-plugin-device-motion 2.0.1 "Device Motion"
cordova-plugin-geolocation 4.0.2 "Geolocation"
cordova-plugin-ionic-keyboard 2.2.0 "cordova-plugin-ionic-keyboard"
cordova-plugin-ionic-webview 4.2.1 "cordova-plugin-ionic-webview"
cordova-plugin-nativegeocoder 3.4.1 "NativeGeocoder"
cordova-plugin-splashscreen 5.0.2 "Splashscreen"
cordova-plugin-statusbar 2.4.2 "StatusBar"
cordova-plugin-whitelist 1.3.3 "Whitelist"