How to wait for Geolocation results?


#1

Hi, all,
Thanks in advance.

I’m using Geolocation API to make application to acquire latitude and longitude.
I want to acquire the latitude and longitude at the initial startup and store it in the global variable.
So I wrote the following code, but ’ionViewDidEnter’ will be executed before success is called.

Test.ts

import { Component } from ‘@angular/core’;
import { NavController, NavParams } from ‘ionic-angular’;
import { Setting } from '…/…/app/variable’
import ‘rxjs/add/operator/map’;

@Component({
selector: ‘page-test’,
templateUrl: ‘test.html’
})

export class TestPage {
constructor(public navCtrl: NavController, public navParams: NavParams) {
navigator.geolocation.getCurrentPosition(function(position) {
Setting.Latitude = position.coords.latitude;
Setting.Longitude = position.coords.longitude;
});
}

ionViewWillLoad(){
     console.log(Setting.Latitude + ' ' + Setting.Longitude );

// Latitde and Longitude are null.
}

ionViewDidLoad() {
    console.log(Setting.Latitude + ' ' + Setting.Longitude );

// Latitde and Longitude are null.
}

ionViewDidEnter(){
    console.log(Setting.Latitude + ' ' + Setting.Longitude );

// Latitde and Longitude are null. I wanna do something here;
}
}

Variable.ts

export class Settings {
public Longitude: number;
public Latitude: number;
constructor() {
this.Longitude = null;
this.Latitude = null;
}
}
export var Setting: Settings;
Setting = new Settings();

I want to get the latitude and longitude in the constructor and then call the first page display “ionViewDidEnter”, but I do not know how.
Please tell me how to wait for results.
Thanks.


#2

Use the ionic-native wrapper that provides Promises.


#3

Thank you for your reply.
It solved in this way!