document.addEventListener("deviceready", onDeviceReady, false);
function onDeviceReady() {
function onSuccess(position) {
this.latitude = position.coords.latitude;
this.longitude = position.coords.longitude;
this.speed = position.coords.speed;
console.log(this.speed);
document.getElementById("updater").innerHTML = ' ' + this.speed +" m/s"
}
function onError(error) {
alert('code: ' + error.code + '\n' +
'message: ' + error.message + '\n');
}
var watchID = navigator.geolocation.watchPosition(this.onSuccess, this.onError, { maximumAge: 3000, timeout: 5000, enableHighAccuracy: true });
}
@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
})
}
}
So, at the top, I placed the listener, which should activate the following function "onDeviceReady()" upon start up of the app. Now I am trying to update an html element.
The element is not updating however, am I approaching this correctly? I am new to typescript.
You are passing this.onSuccess
to .watchPosition
. But onSuccess
here is a local variable, and not a property of the execution context (this
).
That means onSuccess
will never get called.
Leave off the this.
to pass in the locally defined function as the success handler.
var watchID = navigator.geolocation.watchPosition(
onSuccess,
onError,
{
maximumAge: 3000,
timeout: 5000,
enableHighAccuracy: true,
}
);
I'm actually very surprised typescript didn't flag this as an error. I would double check to make sure you've set it up properly.
In fact everywhere you use this
in onSuccess
is just leaking to the global scope. Either create an an object or class that handle this and keeps state, or refactor this to now use this
at all.