Hello ,
I am currently trying to add Geofence in the app using ionic 2. My problem is Geofence in the app does not work all the time. Here is the code -
import { Component } from ‘@angular/core’;
import { AlertController, NavController, Events, MenuController, Platform} from ‘ionic-angular’;
import { locationsPage } from ‘…/locations/locations’;
import { LoginPage } from '…/login/login’
import { settingsPage } from ‘…/settings/settings’;
import { Geolocation } from ‘@ionic-native/geolocation’;
import { Geofence } from ‘@ionic-native/geofence’;
@Component({
selector: ‘page-home’,
templateUrl: ‘home.html’
})
export class HomePage {
constructor(public navCtrl: NavController, private events: Events, private menu: MenuController, private geolocation: Geolocation, private geofence: Geofence, public alertCtrl: AlertController,private platform: Platform) {
this.menu.enable(true, 'menu1');
this.platform.ready().then(() => {
this.geofence.initialize().then(
// resolved promise does not return a value
() => this.showAlert('geofence.initialize'),//console.log('Geofence Plugin Ready'),
(err) => this.showAlert(err)//console.log(err)
);
});
this.geolocation.getCurrentPosition({enableHighAccuracy:true}).then((resp) => {
// resp.coords.latitude
// resp.coords.longitude
//console.log('Geofence Plugin Ready');
let fence = {
id: '61432ec1-b7b1-4c48-90dd-4b91fb30b340', //any unique ID
latitude: resp.coords.latitude, //center of geofence radius
longitude: resp.coords.longitude ,
radius: 100, //radius to edge of geofence in meters
transitionType: 3, //see 'Transition Types' below
notification: { //notification settings
id: 1, //any unique ID
title: 'YOU ARE APPROACHING abc', //notification title
text: 'Welcome.', //notification body
openAppOnClick: true //open app when notification is tapped
}
}
this.geofence.addOrUpdate(fence).then(
() => this.showAlert('geofence.addOrUpdate'),
(err) => this.showAlert('Geofence failed to add: ' + err) //console.log('Geofence failed to add')
);
this.geofence.onTransitionReceived().subscribe(resp => {
this.showAlert('geofence.onTransitionReceived: ' + resp);
});
this.showAlert(resp.coords.latitude + ' - ' + resp.coords.longitude);
}).catch((error) => {
this.showAlert('Error getting location: ' + error.message);//console.log('Error getting location', error);
});
}
showAlert(msg: string) {
let alert = this.alertCtrl.create({
title: msg,
subTitle: msg,
buttons: [‘OK’]
});
alert.present();
}
What can be the possible solution that can make my geofence work everytime I enter/exit that place?