How to use Geolocation, Geofencing and Beacon plugins in Ionic 4

Sanchit Gupta
Mar 12 · 11 min read
Location features are essential in modern day apps
Oops !

1. Geolocation

Here I am !
ionic cordova plugin add cordova-plugin-geolocationnpm install @ionic-native/geolocation
import { Geolocation } from '@ionic-native/geolocation/ngx';

constructor(private geolocation: Geolocation) {}
this.geolocation.getCurrentPosition().then((resp) => {
// resp.coords.latitude
// resp.coords.longitude
}).catch((error) => {
console.log('Error getting location', error);
});
let watch = this.geolocation.watchPosition();
watch.subscribe((data) => {
// data can be a set of coordinates, or an error (if an error occurred).
// data.coords.latitude
// data.coords.longitude
});
https://api.flickr.com/services/rest/?method=flickr.photos.search&api_key=Your_API_Key&lat="
+ latitude + "&lon=" + longitude + "&format=json&jsoncallback=?

2. Geo-fence

Don’t leave that … geofence
ionic cordova plugin add cordova-plugin-geofencenpm install @ionic-native/geofence
import { Geofence } from '@ionic-native/geofence/ngx';


constructor(private geofence: Geofence) {
// initialize the plugin
geofence.initialize().then(
// resolved promise does not return a value
() => console.log('Geofence Plugin Ready'),
(err) => console.log(err)
)
}
private addGeofence() {
//options describing geofence
let fence = {
id: '69ca1b88-6fbe-4e80-a4d4-ff4d3748acdb', //any unique ID
latitude: 37.285951, //center of geofence radius
longitude: -121.936650,
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 crossed a fence', //notification title
text: 'You just arrived to Bangalore city center.', //notification body
openAppOnClick: true //open app when notification is tapped
}
}

this.geofence.addOrUpdate(fence).then(
() => console.log('Geofence added'),
(err) => console.log('Geofence failed to add')
);
}

Javascript background execution

3. Estimote Beacons

Estimote beacons — you beauty
ionic cordova plugin add cordova-plugin-estimotenpm install @ionic-native/estimote-beacons
import { EstimoteBeacons } from '@ionic-native/estimote-beacons/ngx';

constructor(private eb: EstimoteBeacons) { }
// Request permission to use location on iOS
this.eb.requestAlwaysAuthorization();
Monitoring beacons
// Start ranging
this.eb.startMonitoringForRegion(region)
.then(
() => console.log('received the request to monitoring'),
error => console.error('failed to begin monitoring: ', error)
);
// Stop ranging
this.eb.stopMonitoringForRegion()
Ranging Beacons
// Start ranging
this.eb.startRangingBeaconsInRegion(region)
.then(
() => console.log('received the request to monitoring'),
error => console.error('failed to begin monitoring: ', error)
);
// Stop ranging
this.eb.stopRangingBeaconsInRegion()

4. iBeacon

Use beacons for shopping related apps
ionic cordova plugin add cordova-plugin-ibeaconnpm install @ionic-native/ibeacon
import { IBeacon } from '@ionic-native/ibeacon/ngx';

constructor(private ibeacon: IBeacon) { }
// Request permission to use location on iOS
this.ibeacon.requestAlwaysAuthorization();
// create a new delegate and register it with the native layer
let delegate = this.ibeacon.Delegate();

// Subscribe to some of the delegate's event handlers
delegate.didRangeBeaconsInRegion()
.subscribe(
data => console.log('didRangeBeaconsInRegion: ', data),
error => console.error()
);
delegate.didStartMonitoringForRegion()
.subscribe(
data => console.log('didStartMonitoringForRegion: ', data),
error => console.error()
);
delegate.didEnterRegion()
.subscribe(
data => {
console.log('didEnterRegion: ', data);
}
);
let beaconRegion = this.ibeacon.BeaconRegion('deskBeacon','F7826DA6-ASDF-ASDF-8024-BC5B71E0893E');

this.ibeacon.startMonitoringForRegion(beaconRegion)
.then(
() => console.log('Native layer received the request to monitoring'),
error => console.error('Native layer failed to begin monitoring: ', error)
);

5. NFC

Near-field communication can be used for payments
ionic cordova plugin add phonegap-nfcnpm install @ionic-native/nfc
import { NFC, Ndef } from '@ionic-native/nfc/ngx';

constructor(private nfc: NFC, private ndef: Ndef) { }
this.nfc.addNdefListener(() => {
console.log('successfully attached ndef listener');
}, (err) => {
console.log('error attaching ndef listener', err);
}).subscribe((event) => {
console.log('received ndef message. the tag contains: ', event.tag);
console.log('decoded tag id', this.nfc.bytesToHexString(event.tag.id));

let message = this.ndef.textRecord('Hello world');
this.nfc.share([message]).then(onSuccess).catch(onError);
});

6. Native Geocoder

Geocoding and reverse-geocoding — It’s all Math :|
ionic cordova plugin add cordova-plugin-nativegeocodernpm install @ionic-native/native-geocoder
import { NativeGeocoder, NativeGeocoderReverseResult, NativeGeocoderForwardResult, NativeGeocoderOptions } from '@ionic-native/native-geocoder/ngx';

constructor(private nativeGeocoder: NativeGeocoder) { }
let options: NativeGeocoderOptions = {
useLocale: true,
maxResults: 5
};

this.nativeGeocoder.reverseGeocode(52.5072095, 13.1452818, options)
.then((result: NativeGeocoderReverseResult[]) => console.log(JSON.stringify(result[0])))
.catch((error: any) => console.log(error));

this.nativeGeocoder.forwardGeocode('Berlin', options)
.then((coordinates: NativeGeocoderForwardResult[]) => console.log('The coordinates are latitude=' + coordinates[0].latitude + ' and longitude=' + coordinates[0].longitude))
.catch((error: any) => console.log(error));

7. Location Accuracy

In today’s world, location accuracy is paramount
Turn left at .. the .. what
ionic cordova plugin add cordova-plugin-request-location-accuracynpm install @ionic-native/location-accuracy
import { LocationAccuracy } from '@ionic-native/location-accuracy/ngx';

constructor(private locationAccuracy: LocationAccuracy) { }
this.locationAccuracy.canRequest().then((canRequest: boolean) => {

if(canRequest) {
// the accuracy option will be ignored by iOS
this.locationAccuracy.request(this.locationAccuracy.REQUEST_PRIORITY_HIGH_ACCURACY).then(
() => console.log('Request successful'),
error => console.log('Error requesting location permissions', error)
);
}

});

Conclusion

FOUND THIS POST INTERESTING ?

NEED FREE IONIC 4 STARTERS?

References


Enappd

App starters, Themes, Templates, Complete Web and Mobile Apps Solutions

Sanchit Gupta

Written by

Author at enappd.com

Enappd

Enappd

App starters, Themes, Templates, Complete Web and Mobile Apps Solutions