How to use Geolocation, Geofencing and Beacon plugins in Ionic 4
Tags: ionic, geolocation, geofencing, beacons
Published: 2019-09-11 15:31:58

<main role="main"><article class=" u-minHeight100vhOffset65 u-overflowHidden postArticle postArticle--full is-withAccentColors" lang="en"><div class="postArticle-content js-postField js-notesSource editable" id="editor_6" g_editable="true" role="textbox" contenteditable="true" data-default-value="Title
Tell your story…" spellcheck="false"><section name="922f" class="section section--body section--first"><div class="section-divider"><hr class="section-divider"></div><div class="section-content"><div class="section-inner sectionLayout--insetColumn"><p name="9c6f" class="graf graf--p graf-after--figure">Geolocation, GPS are not fancy words for anyone today. Every smart phone user knows they can use GPS to know their location in the world (in Google/Apple Map). Famous apps like Uber, Lyft make use of location data to book rides, etc. Apps for food delivery use GPS data for live tracking the delivery person.</p><p name="faae" class="graf graf--p graf-after--p">There are several interesting features and plugins available in Ionic 4 to get the best out of a user’s location. These include near-field as well as GPS based location features. In this blog, we explore these features in depth, and how to use them in our own Ionic app. Let’s dive right in</p><figure tabindex="0" contenteditable="false" name="8fcb" class="graf graf--figure graf-after--p"><div class="aspectRatioPlaceholder is-locked" style="max-width: 250px; max-height: 184px;"><div class="aspectRatioPlaceholder-fill" style="padding-bottom: 73.6%;"></div><img class="graf-image" data-image-id="1*0NA5jF7TPKN7JLD3kHkrRA.gif" data-width="250" data-height="184" src="https://cdn-images-1.medium.com/max/720/1*0NA5jF7TPKN7JLD3kHkrRA.gif"><div class="crosshair u-ignoreBlock"></div></div><br/><figcaption class="imageCaption" contenteditable="true" data-default-value="Type caption for image (optional)">Oops&nbsp;!</figcaption></figure><h3 name="7739" class="graf graf--h3 graf-after--figure is-selected">1. Geolocation</h3><figure tabindex="0" contenteditable="false" name="55c4" class="graf graf--figure graf-after--h3"><div class="aspectRatioPlaceholder is-locked" style="max-width: 700px; max-height: 469px;"><div class="aspectRatioPlaceholder-fill" style="padding-bottom: 67%;"></div><img class="graf-image" data-image-id="1*jMwuqtMWN1bLZFw_Eh4YQg.jpeg" data-width="960" data-height="643" src="https://cdn-images-1.medium.com/max/720/1*jMwuqtMWN1bLZFw_Eh4YQg.jpeg"><div class="crosshair u-ignoreBlock"></div></div><br/><figcaption class="imageCaption" contenteditable="true" data-default-value="Type caption for image (optional)">Here I am&nbsp;!</figcaption></figure><p name="a407" class="graf graf--p graf-after--figure">The most famous and familiar location feature&#8202;—&#8202;Geolocation is the ability to track a device’s whereabouts using GPS, cell phone towers, WiFi access points or a combination of these. Since devices are used by individuals, geolocation uses positioning systems to track an individual’s whereabouts down to latitude and longitude coordinates, or more practically, a physical address. Both mobile and desktop devices can use geolocation.<br>Geolocation can be used to determine time zone and exact positioning coordinates, such as for tracking wildlife or cargo shipments.</p><p name="b122" class="graf graf--p graf-after--p">Some famous apps using Geolocation are</p><ul class="postList"><li name="43f4" class="graf graf--li graf-after--p">Uber / Lyft&#8202;—&#8202;Cab booking</li><li name="e8bd" class="graf graf--li graf-after--li">Google Maps (of course)&#8202;—&#8202;Map services</li><li name="90ff" class="graf graf--li graf-after--li">Swiggy / Zomato&#8202;—&#8202;Food delivery</li><li name="1801" class="graf graf--li graf-after--li">Fitbit&#8202;—&#8202;Fitness app</li><li name="fc18" class="graf graf--li graf-after--li">Instagram / Facebook&#8202;—&#8202;For tagging photos</li></ul><p name="51bb" class="graf graf--p graf-after--li">Let’s see briefly how we can use Geolocation in our Ionic 4 app. To install the plugin use</p><pre name="2e19" class="graf graf--pre graf-after--p">ionic cordova plugin add cordova-plugin-geolocation</pre><pre name="c3d9" class="graf graf--pre graf-after--pre">npm install @ionic-native/geolocation</pre><p name="693d" class="graf graf--p graf-after--pre">For all plugins, the step to import the plugin in a component will remain common (just change the plugin name)</p><pre name="ef64" class="graf graf--pre graf-after--p"><code class="markup--code markup--pre-code">import { Geolocation } from '@ionic-native/geolocation/ngx';<br><br>constructor(private geolocation: Geolocation) {}</code></pre><p name="3b66" class="graf graf--p graf-after--pre">Once the plugin is imported, (and make sure the deviceReady has fired), you can find current location using</p><pre name="8ef4" class="graf graf--pre graf-after--p"><code class="markup--code markup--pre-code u-paddingRight0 u-marginRight0">this.geolocation.<strong class="markup--strong markup--pre-strong">getCurrentPosition</strong>().then((resp) =&gt; {<br> // resp.coords.latitude<br> // resp.coords.longitude<br>}).catch((error) =&gt; {<br>  console.log('Error getting location', error);<br>});</code></pre><p name="0435" class="graf graf--p graf-after--pre">If you want a continuous tracking of your location, use this instead</p><pre name="1eb8" class="graf graf--pre graf-after--p"><code class="markup--code markup--pre-code u-paddingRight0 u-marginRight0">let watch = this.geolocation.<strong class="markup--strong markup--pre-strong">watchPosition</strong>();<br>watch.subscribe((data) =&gt; {<br> // data can be a set of coordinates, or an error (if an error occurred).<br> // data.coords.latitude<br> // data.coords.longitude<br>});</code></pre><p name="263e" class="graf graf--p graf-after--pre">These are the very basics of Geolocation, but you can do a lot more using basic free and open-source APIs. Once you have your location, you can</p><ul class="postList"><li name="6643" class="graf graf--li graf-after--p">Find out the weather in your location using open weather API from <a href="http://openweathermap.org/"  class="markup--anchor markup--li-anchor" rel="noopener" target="_blank">http://openweathermap.org/</a></li><li name="a3d0" class="graf graf--li graf-after--li">Locate yourself on map by using Google Map in your app, and setting a marker on your location</li><li name="1971" class="graf graf--li graf-after--li">Find nearby restaurants by using Google Map API</li><li name="dca0" class="graf graf--li graf-after--li">See pictures of things around you using <code class="markup--code markup--li-code">Flickr</code> API</li></ul><pre name="30af" class="graf graf--pre graf-after--li">https://api.flickr.com/services/rest/?method=flickr.photos.search&amp;api_key=Your_API_Key&amp;lat="<br>    + latitude + "&amp;lon=" + longitude + "&amp;format=json&amp;jsoncallback=?</pre><p name="e03d" class="graf graf--p graf-after--pre">For more information on the plugin, you can visit <a href="https://github.com/apache/cordova-plugin-geolocation"  class="markup--anchor markup--p-anchor" rel="nofollow noopener" target="_blank">https://github.com/apache/cordova-plugin-geolocation</a></p><h3 name="5374" class="graf graf--h3 graf-after--p">2. Geo-fence</h3><figure tabindex="0" contenteditable="false" name="34cb" class="graf graf--figure graf-after--h3"><div class="aspectRatioPlaceholder is-locked" style="max-width: 700px; max-height: 492px;"><div class="aspectRatioPlaceholder-fill" style="padding-bottom: 70.3%;"></div><img class="graf-image" data-image-id="1*BKPmLdCQtQPxC5acF40fdQ.jpeg" data-width="757" data-height="532" src="https://cdn-images-1.medium.com/max/720/1*BKPmLdCQtQPxC5acF40fdQ.jpeg"><div class="crosshair u-ignoreBlock"></div></div><br/><figcaption class="imageCaption" contenteditable="true" data-default-value="Type caption for image (optional)">Don’t leave that&nbsp;…&nbsp;geofence</figcaption></figure><p name="c78b" class="graf graf--p graf-after--figure">A <strong class="markup--strong markup--p-strong">geo-fence</strong> is a <a href="https://en.wikipedia.org/wiki/Virtuality"  class="markup--anchor markup--p-anchor" title="Virtuality" rel="noopener"    target="_blank">virtual</a> <a href="https://en.wikipedia.org/wiki/Perimeter"  class="markup--anchor markup--p-anchor" title="Perimeter" rel="noopener"    target="_blank">perimeter</a> for a real-world <a href="https://en.wikipedia.org/wiki/Geographic_area"  class="markup--anchor markup--p-anchor" title="Geographic area" rel="noopener"    target="_blank">geographic area</a>. Geofencing combines awareness of the user’s current location with awareness of the user’s proximity to locations that may be of interest. Imagine an area drawn on the map, and you are supposed to stay inside (or outside) this area. This is a perfect use case for Geofencing.</p><p name="fcc4" class="graf graf--p graf-after--p">To mark a location of interest, you specify its latitude and longitude. To adjust the proximity for the location, you add a radius. The latitude, longitude, and radius define a geofence, creating a circular area, or fence, around the location of interest.</p><p name="ad53" class="graf graf--p graf-after--p">Some good use cases for geofencing are</p><ul class="postList"><li name="98ba" class="graf graf--li graf-after--p"><a href="https://en.wikipedia.org/wiki/Parental_controls"  class="markup--anchor markup--li-anchor" rel="noopener"    target="_blank">Child location</a> services, can notify parents if a child leaves a designated area.</li><li name="93ae" class="graf graf--li graf-after--li">Prison areas or highly sensitive government buildings can be Geofenced and every person entering / working in the area can be tracked</li><li name="c656" class="graf graf--li graf-after--li">A quarantined area can be marked as hazard on map, and an app can alert you if you are about to enter that area</li></ul><p name="2458" class="graf graf--p graf-after--li">So let’s see briefly how we can use Geofencing in our Ionic 4 app. To install the plugin use</p><pre name="43ba" class="graf graf--pre graf-after--p">ionic cordova plugin add cordova-plugin-geofence</pre><pre name="1c7a" class="graf graf--pre graf-after--pre">npm install @ionic-native/geofence</pre><p name="ecfa" class="graf graf--p graf-after--pre">For all plugins, the step to import the plugin in a component will remain common (just change the plugin name)</p><pre name="220e" class="graf graf--pre graf-after--p"><code class="markup--code markup--pre-code">import { Geofence } from '@ionic-native/geofence/ngx';<br><br><br>constructor(private geofence: Geofence) {<br>  // initialize the plugin<br>  geofence.initialize().then(<br>    // resolved promise does not return a value<br>    () =&gt; console.log('Geofence Plugin Ready'),<br>    (err) =&gt; console.log(err)<br>  )<br>}</code></pre><p name="ac55" class="graf graf--p graf-after--pre">Once the plugin is imported and initialized, you can add a Geofence using</p><pre name="d545" class="graf graf--pre graf-after--p"><code class="markup--code markup--pre-code u-paddingRight0 u-marginRight0">private addGeofence() {<br>  //options describing geofence<br>  let fence = {<br>    id: '69ca1b88-6fbe-4e80-a4d4-ff4d3748acdb', //any unique ID<br>    latitude:       37.285951, //center of geofence radius<br>    longitude:      -121.936650,<br>    radius:         100, //radius to edge of geofence in meters<br>    transitionType: 3, //see 'Transition Types' below<br>    notification: { //notification settings<br>        id:             1, //any unique ID<br>        title:          'You crossed a fence', //notification title<br>        text:           'You just arrived to Bangalore city center.', //notification body<br>        openAppOnClick: true //open app when notification is tapped<br>    }<br>  }<br><br>  this.geofence.<strong class="markup--strong markup--pre-strong">addOrUpdate</strong>(fence).then(<br>     () =&gt; console.log('Geofence added'),<br>     (err) =&gt; console.log('Geofence failed to add')<br>   );<br>}</code></pre><p name="1256" class="graf graf--p graf-after--pre"><code class="markup--code markup--p-code">transitionType</code> is used to define which transition of user should trigger an alert. It supports three values</p><ul class="postList"><li name="b6d4" class="graf graf--li graf-after--p">1: Enter</li><li name="8ef8" class="graf graf--li graf-after--li">2: Leave</li><li name="1635" class="graf graf--li graf-after--li">3: Both</li></ul><p name="aae9" class="graf graf--p graf-after--li">You can override default <code class="markup--code markup--p-code">transition</code> behavior by overriding <code class="markup--code markup--p-code">this.geofence.onTransitionReceived()</code> function.</p><p name="718c" class="graf graf--p graf-after--p"><code class="markup--code markup--p-code">this.geofence.remove()</code> will remove a geofence with specific Id, and hence stops tracking as well.</p><h4 name="bfbf" class="graf graf--h4 graf-after--p">Javascript background execution</h4><p name="90d8" class="graf graf--p graf-after--h4">This is a known limitation. When in background, your app may/will be suspended to not use system resources. Therefore, any javascript code won’t run, only background services can run in the background. Local notification when user crosses a geofence region will still work, but any custom javascript code won’t. If you want to perform a custom action on geofence crossing, <a href="https://github.com/cowbell/cordova-plugin-geofence#listening-for-geofence-transitions-in-native-code"  class="markup--anchor markup--p-anchor" rel="noopener"    target="_blank">try to write it in native code</a>.</p><h3 name="ef7e" class="graf graf--h3 graf-after--p">3. Estimote&nbsp;Beacons</h3><figure tabindex="0" contenteditable="false" name="538f" class="graf graf--figure graf-after--h3"><div class="aspectRatioPlaceholder is-locked" style="max-width: 700px; max-height: 617px;"><div class="aspectRatioPlaceholder-fill" style="padding-bottom: 88.1%;"></div><a href="https://estimote.com/"  class="graf-imageAnchor" data-action="image-link" data-action-observe-only="true" rel="noopener" target="_blank"   ><img class="graf-image" data-image-id="1*HyPbD8Ibb3Ju18TW6os0pA.jpeg" data-width="700" data-height="617" src="https://cdn-images-1.medium.com/max/720/1*HyPbD8Ibb3Ju18TW6os0pA.jpeg"><div class="crosshair u-ignoreBlock"></div></a></div><br/><figcaption class="imageCaption" contenteditable="true" data-default-value="Type caption for image (optional)">Estimote beacons&#8202;—&#8202;you&nbsp;beauty</figcaption></figure><p name="e806" class="graf graf--p graf-after--figure">Things get a little nerdy here. Estimote beacons are near field sensors which sense nearby devices. These wireless sensors (beacons) communicate with apps on a mobile device to trigger contextually relevant actions, from personalized notifications and frictionless payments to indoor navigation and automations.</p><p name="b2d5" class="graf graf--p graf-after--p">Imagine walking around in a shopping mall. You might not want to go inside every shop and explore the things on display, or what offers are available etc. A beacon from each shop, or from a central location can send notifications to your app and tell you what offers are available so you can pick the right one.</p><p name="87c8" class="graf graf--p graf-after--p">Let’s quickly see how we can use Estimote Beacons in our Ionic 4 app. First of all, to use this feature, you need the <strong class="markup--strong markup--p-strong">beacons</strong>. These are available on <a href="https://estimote.com/"  class="markup--anchor markup--p-anchor" rel="noopener"    target="_blank">Estimote website</a>. To install the plugin use</p><pre name="b5d4" class="graf graf--pre graf-after--p">ionic cordova plugin add cordova-plugin-estimote</pre><pre name="a05d" class="graf graf--pre graf-after--pre">npm install @ionic-native/estimote-beacons</pre><p name="78c3" class="graf graf--p graf-after--pre">Import the plugin in a component with</p><pre name="3d00" class="graf graf--pre graf-after--p"><code class="markup--code markup--pre-code">import { EstimoteBeacons } from '@ionic-native/estimote-beacons/ngx';<br><br>constructor(private eb: EstimoteBeacons) { }</code></pre><pre name="45e2" class="graf graf--pre graf-after--pre"><code class="markup--code markup--pre-code">// Request permission to use location on iOS<br>this.eb.requestAlwaysAuthorization();</code></pre><p name="4060" class="graf graf--p graf-after--pre">Apps detect and interact with beacons in two ways:</p><ul class="postList"><li name="4148" class="graf graf--li graf-after--p">Monitoring: actions triggered on entering/exiting region’s range; <strong class="markup--strong markup--li-strong">works no matter whether the app is running, suspended, or killed</strong> (if the app’s not running when an enter/exit even comes, iOS will launch it into the background for a few seconds to handle the event)</li></ul><figure tabindex="0" contenteditable="false" name="8b30" class="graf graf--figure graf-after--li"><div class="aspectRatioPlaceholder is-locked" style="max-width: 600px; max-height: 407px;"><div class="aspectRatioPlaceholder-fill" style="padding-bottom: 67.80000000000001%;"></div><img class="graf-image" data-image-id="1*vwOt4RtZjjHVi6HRlXYbmA.png" data-width="600" data-height="407" src="https://cdn-images-1.medium.com/max/720/1*vwOt4RtZjjHVi6HRlXYbmA.png"><div class="crosshair u-ignoreBlock"></div></div><br/><figcaption class="imageCaption" contenteditable="true" data-default-value="Type caption for image (optional)">Monitoring beacons</figcaption></figure><p name="1a0c" class="graf graf--p graf-after--figure">Once the plugin is imported and initialized, you can use monitoring functions</p><pre name="867c" class="graf graf--pre graf-after--p">// Start ranging<br>this.eb.<code class="markup--code markup--pre-code">startMonitoringForRegion(region)<br>  .then(<br>    () =&gt; console.log('received the request to monitoring'),<br>    error =&gt; console.error('failed to begin monitoring: ', error)<br>  );</code></pre><pre name="1b00" class="graf graf--pre graf-after--pre">// Stop ranging<br>this.eb.<code class="markup--code markup--pre-code">stopMonitoringForRegion()</code></pre><ul class="postList"><li name="4335" class="graf graf--li graf-after--pre">Ranging: actions triggered based on proximity to a beacon; works <strong class="markup--strong markup--li-strong">only when the app is running</strong>(e.g., it’s displayed on screen, or running in the background in response to a monitoring event, etc.)</li></ul><figure tabindex="0" contenteditable="false" name="eebb" class="graf graf--figure graf-after--li"><div class="aspectRatioPlaceholder is-locked" style="max-width: 600px; max-height: 527px;"><div class="aspectRatioPlaceholder-fill" style="padding-bottom: 87.8%;"></div><img class="graf-image" data-image-id="1*j-L2H8qtFoSX80l9ITAZMw.png" data-width="600" data-height="527" src="https://cdn-images-1.medium.com/max/720/1*j-L2H8qtFoSX80l9ITAZMw.png"><div class="crosshair u-ignoreBlock"></div></div><br/><figcaption class="imageCaption" contenteditable="true" data-default-value="Type caption for image (optional)">Ranging Beacons</figcaption></figure><p name="6f26" class="graf graf--p graf-after--figure">Once the plugin is imported and initialized, you can use ranging functions</p><pre name="f8c5" class="graf graf--pre graf-after--p">// Start ranging<br>this.eb.<code class="markup--code markup--pre-code">startRangingBeaconsInRegion(region)<br>  .then(<br>    () =&gt; console.log('received the request to monitoring'),<br>    error =&gt; console.error('failed to begin monitoring: ', error)<br>  );</code></pre><pre name="bfd0" class="graf graf--pre graf-after--pre">// Stop ranging<br>this.eb.<code class="markup--code markup--pre-code">stopRangingBeaconsInRegion()</code></pre><p name="f3fb" class="graf graf--p graf-after--pre">It’s important to remember that Monitoring allows you to scan for beacon regions, while Ranging is for interacting with individual beacons.</p><p name="f7ad" class="graf graf--p graf-after--p">There is a lot of trial and error with this plugin. In absence of a real beacon, you can use a <a href="https://itunes.apple.com/us/app/estimote-virtual-beacon/id686915066"  class="markup--anchor markup--p-anchor" rel="noopener"    target="_blank">beacon emulator app</a>, which acts like a demo beacon.</p><h3 name="c9a6" class="graf graf--h3 graf-after--p">4. iBeacon</h3><figure tabindex="0" contenteditable="false" name="f915" class="graf graf--figure graf-after--h3"><div class="aspectRatioPlaceholder is-locked" style="max-width: 700px; max-height: 403px;"><div class="aspectRatioPlaceholder-fill" style="padding-bottom: 57.599999999999994%;"></div><img class="graf-image" data-image-id="1*59YzS8rqCyqVMdp3cFxlCw.jpeg" data-width="990" data-height="570" src="https://cdn-images-1.medium.com/max/720/1*59YzS8rqCyqVMdp3cFxlCw.jpeg"><div class="crosshair u-ignoreBlock"></div></div><br/><figcaption class="imageCaption" contenteditable="true" data-default-value="Type caption for image (optional)">Use beacons for shopping related&nbsp;apps</figcaption></figure><p name="889b" class="graf graf--p graf-after--figure">This is very much similar to Estimote beacon technology. <strong class="markup--strong markup--p-strong">iBeacon</strong> is the name for Apple’s technology standard, which allows Mobile Apps (running on both iOS and Android devices) to listen for signals from beacons in the physical world and react accordingly. In essence, iBeacon technology allows Mobile Apps <a href="http://www.ibeacon.com/apples-ibeacon-future-mobile-shopping/"  class="markup--anchor markup--p-anchor" rel="noopener"    target="_blank">to understand their position</a> on a micro-local scale, and deliver hyper-contextual content to users based on location. The underlying communication technology is Bluetooth Low Energy (BLE).</p><p name="2415" class="graf graf--p graf-after--p">BLE communication consists primarily of “Advertisements”, or small packets of data, broadcast at a regular interval by Beacons or other BLE enabled devices via radio waves. These packets are meant to be collected by devices like smartphones, where they can be used for a variety of smartphone applications to trigger things like push messages, app actions, and prompts.<br>Standard BLE has a broadcast range of up to 100 meters, which make Beacons ideal for indoor location tracking and awareness.</p><p name="9f83" class="graf graf--p graf-after--p">To install the plugin use</p><pre name="0b86" class="graf graf--pre graf-after--p">ionic cordova plugin add cordova-plugin-ibeacon</pre><pre name="79cb" class="graf graf--pre graf-after--pre">npm install @ionic-native/ibeacon</pre><p name="8749" class="graf graf--p graf-after--pre">Import the plugin in a component with and start using</p><pre name="2369" class="graf graf--pre graf-after--p"><code class="markup--code markup--pre-code">import { IBeacon } from '@ionic-native/ibeacon/ngx';<br><br>constructor(private ibeacon: IBeacon) { }</code></pre><pre name="2209" class="graf graf--pre graf-after--pre"><code class="markup--code markup--pre-code">// Request permission to use location on iOS<br>this.ibeacon.requestAlwaysAuthorization();</code></pre><pre name="e71e" class="graf graf--pre graf-after--pre"><code class="markup--code markup--pre-code">// create a new delegate and register it with the native layer<br>let delegate = this.ibeacon.Delegate();<br><br>// Subscribe to some of the delegate's event handlers<br>delegate.didRangeBeaconsInRegion()<br>  .subscribe(<br>    data =&gt; console.log('didRangeBeaconsInRegion: ', data),<br>    error =&gt; console.error()<br>  );<br>delegate.didStartMonitoringForRegion()<br>  .subscribe(<br>    data =&gt; console.log('didStartMonitoringForRegion: ', data),<br>    error =&gt; console.error()<br>  );<br>delegate.didEnterRegion()<br>  .subscribe(<br>    data =&gt; {<br>      console.log('didEnterRegion: ', data);<br>    }<br>  );</code></pre><p name="7ce5" class="graf graf--p graf-after--pre">You can create a beacon region with a name and UUID</p><pre name="15aa" class="graf graf--pre graf-after--p"><code class="markup--code markup--pre-code u-paddingRight0 u-marginRight0">let beaconRegion = this.ibeacon.BeaconRegion('deskBeacon','F7826DA6-ASDF-ASDF-8024-BC5B71E0893E');<br><br>this.ibeacon.<strong class="markup--strong markup--pre-strong">startMonitoringForRegion</strong>(beaconRegion)<br>  .then(<br>    () =&gt; console.log('Native layer received the request to monitoring'),<br>    error =&gt; console.error('Native layer failed to begin monitoring: ', error)<br>  );</code></pre><p name="8c50" class="graf graf--p graf-after--pre">You can check more details of the plugin here&#8202;—&#8202;<a href="https://github.com/petermetz/cordova-plugin-ibeacon"  class="markup--anchor markup--p-anchor" rel="nofollow noopener" target="_blank">https://github.com/petermetz/cordova-plugin-ibeacon</a></p><h3 name="9400" class="graf graf--h3 graf-after--p">5. NFC</h3><figure tabindex="0" contenteditable="false" name="e57b" class="graf graf--figure graf-after--h3"><div class="aspectRatioPlaceholder is-locked" style="max-width: 700px; max-height: 462px;"><div class="aspectRatioPlaceholder-fill" style="padding-bottom: 66%;"></div><img class="graf-image" data-image-id="1*N-23r5K36M7qQDMYcNS6Vw.jpeg" data-width="770" data-height="508" src="https://cdn-images-1.medium.com/max/720/1*N-23r5K36M7qQDMYcNS6Vw.jpeg"><div class="crosshair u-ignoreBlock"></div></div><br/><figcaption class="imageCaption" contenteditable="true" data-default-value="Type caption for image (optional)">Near-field communication can be used for&nbsp;payments</figcaption></figure><p name="f3de" class="graf graf--p graf-after--figure"><strong class="markup--strong markup--p-strong">Near-field communication</strong> (<strong class="markup--strong markup--p-strong">NFC</strong>) is a set of <a href="https://en.wikipedia.org/wiki/Communications_protocol"  class="markup--anchor markup--p-anchor" title="Communications protocol" rel="noopener"    target="_blank">communication protocols</a> that enable two electronic devices, one of which is usually a portable device such as a <a href="https://en.wikipedia.org/wiki/Smartphone"  class="markup--anchor markup--p-anchor" title="Smartphone" rel="noopener"    target="_blank">smartphone</a>, to establish <a href="https://en.wikipedia.org/wiki/Data_communication"  class="markup--anchor markup--p-anchor" title="Data communication" rel="noopener"    target="_blank">communication</a> by bringing them within 4 cm (1.6 in) of each other.</p><p name="5a29" class="graf graf--p graf-after--p">NFC devices are used in <a href="https://en.wikipedia.org/wiki/Contactless_payment"  class="markup--anchor markup--p-anchor" title="Contactless payment" rel="noopener"    target="_blank">contactless payment</a> systems, similar to those used in credit cards and <a href="https://en.wikipedia.org/wiki/Electronic_ticket"  class="markup--anchor markup--p-anchor" title="Electronic ticket" rel="noopener"    target="_blank">electronic ticket</a> smartcards and allow <a href="https://en.wikipedia.org/wiki/Mobile_payment"  class="markup--anchor markup--p-anchor" title="Mobile payment" rel="noopener"    target="_blank">mobile payment</a> to replace or supplement these systems.</p><p name="58d8" class="graf graf--p graf-after--p">NFC can also be used for <a href="https://en.wikipedia.org/wiki/Social_networking_service"  class="markup--anchor markup--p-anchor" title="Social networking service" rel="noopener"    target="_blank">social networking</a>, for sharing contacts, photos, videos or files. NFC-enabled devices can act as electronic <a href="https://en.wikipedia.org/wiki/Identity_document"  class="markup--anchor markup--p-anchor" title="Identity document" rel="noopener"    target="_blank">identity documents</a> and <a href="https://en.wikipedia.org/wiki/Keycard_lock"  class="markup--anchor markup--p-anchor" title="Keycard lock" rel="noopener"    target="_blank">keycards</a>. NFC transfers are usually faster and easier to perform than most other transfer methods.</p><p name="a4c2" class="graf graf--p graf-after--p">To install the plugin use</p><pre name="fb7d" class="graf graf--pre graf-after--p">ionic cordova plugin add phonegap-nfc</pre><pre name="e259" class="graf graf--pre graf-after--pre">npm install @ionic-native/nfc</pre><p name="e8b0" class="graf graf--p graf-after--pre">Import the plugin in a component with</p><pre name="c2e0" class="graf graf--pre graf-after--p"><code class="markup--code markup--pre-code">import { NFC, Ndef } from '@ionic-native/nfc/ngx';<br><br>constructor(private nfc: NFC, private ndef: Ndef) { }</code></pre><p name="23fa" class="graf graf--p graf-after--pre">Then start using the NFC plugin with a listener</p><pre name="ad24" class="graf graf--pre graf-after--p"><code class="markup--code markup--pre-code u-paddingRight0 u-marginRight0">this.nfc.<strong class="markup--strong markup--pre-strong">addNdefListener</strong>(() =&gt; {<br>  console.log('successfully attached ndef listener');<br>}, (err) =&gt; {<br>  console.log('error attaching ndef listener', err);<br>}).subscribe((event) =&gt; {<br>  console.log('received ndef message. the tag contains: ', event.tag);<br>  console.log('decoded tag id', this.nfc.bytesToHexString(event.tag.id));<br><br>  let message = this.ndef.textRecord('Hello world');<br>  this.nfc.share([message]).then(onSuccess).catch(onError);<br>});</code></pre><p name="128c" class="graf graf--p graf-after--pre"><code class="markup--code markup--p-code">removeNdefListener</code> removes the previously started listener.</p><p name="9edd" class="graf graf--p graf-after--p"><code class="markup--code markup--p-code">addTagDiscoveredListener</code> registers an event listener for tags matching any tag type.</p><p name="5ed2" class="graf graf--p graf-after--p"><code class="markup--code markup--p-code">removeTagDiscoveredListener</code> removes the previously registered event listener added via <code class="markup--code markup--p-code">nfc.addTagDiscoveredListener</code>.</p><p name="1013" class="graf graf--p graf-after--p">For details on the functions and issues, you can visit <a href="https://github.com/chariotsolutions/phonegap-nfc#nfcaddndeflistener"  class="markup--anchor markup--p-anchor" rel="nofollow noopener" target="_blank">https://github.com/chariotsolutions/phonegap-nfc#nfcaddndeflistener</a></p><h3 name="bd4f" class="graf graf--h3 graf-after--p">6. Native&nbsp;Geocoder</h3><figure tabindex="0" contenteditable="false" name="c603" class="graf graf--figure graf-after--h3"><div class="aspectRatioPlaceholder is-locked" style="max-width: 700px; max-height: 424px;"><div class="aspectRatioPlaceholder-fill" style="padding-bottom: 60.5%;"></div><img class="graf-image" data-image-id="1*0NRzuwKO1AV7ybT_iIE5sQ.jpeg" data-width="760" data-height="460" src="https://cdn-images-1.medium.com/max/720/1*0NRzuwKO1AV7ybT_iIE5sQ.jpeg"><div class="crosshair u-ignoreBlock"></div></div><br/><figcaption class="imageCaption" contenteditable="true" data-default-value="Type caption for image (optional)">Geocoding and reverse-geocoding&#8202;—&#8202;It’s all Math&nbsp;:|</figcaption></figure><p name="b20d" class="graf graf--p graf-after--figure"><strong class="markup--strong markup--p-strong">Geocoding</strong> is the process of transforming a street address or other description of a location into a (latitude, longitude) coordinate.&nbsp;<br><strong class="markup--strong markup--p-strong">Reverse geocoding</strong> is the process of transforming a (latitude, longitude) coordinate into a (partial) address. The amount of detail in a reverse geocoded location description may vary, for example one might contain the full street address of the closest building, while another might contain only a city name and postal code.</p><p name="76c2" class="graf graf--p graf-after--p">To install the plugin use</p><pre name="0578" class="graf graf--pre graf-after--p">ionic cordova plugin add cordova-plugin-nativegeocoder</pre><pre name="688d" class="graf graf--pre graf-after--pre">npm install @ionic-native/native-geocoder</pre><p name="c6ab" class="graf graf--p graf-after--pre">Import the plugin in a component with</p><pre name="4f06" class="graf graf--pre graf-after--p"><code class="markup--code markup--pre-code">import { NativeGeocoder, NativeGeocoderReverseResult, NativeGeocoderForwardResult, NativeGeocoderOptions } from '@ionic-native/native-geocoder/ngx';<br><br>constructor(private nativeGeocoder: NativeGeocoder) { }</code></pre><p name="ea0c" class="graf graf--p graf-after--pre">Then start using the geocoding plugin with</p><pre name="44f5" class="graf graf--pre graf-after--p"><code class="markup--code markup--pre-code">let options: NativeGeocoderOptions = {<br>    useLocale: true,<br>    maxResults: 5<br>};<br><br>this.nativeGeocoder.reverseGeocode(52.5072095, 13.1452818, options)<br>  .then((result: NativeGeocoderReverseResult[]) =&gt; console.log(JSON.stringify(result[0])))<br>  .catch((error: any) =&gt; console.log(error));<br><br>this.nativeGeocoder.forwardGeocode('Berlin', options)<br>  .then((coordinates: NativeGeocoderForwardResult[]) =&gt; console.log('The coordinates are latitude=' + coordinates[0].latitude + ' and longitude=' + coordinates[0].longitude))<br>  .catch((error: any) =&gt; console.log(error));</code></pre><h3 name="8a31" class="graf graf--h3 graf-after--pre">7. Location&nbsp;Accuracy</h3><figure tabindex="0" contenteditable="false" name="6387" class="graf graf--figure graf-after--h3"><div class="aspectRatioPlaceholder is-locked" style="max-width: 500px; max-height: 331px;"><div class="aspectRatioPlaceholder-fill" style="padding-bottom: 66.2%;"></div><img class="graf-image" data-image-id="1*weFF698N91q7xd1VdC01uw.jpeg" data-width="500" data-height="331" src="https://cdn-images-1.medium.com/max/720/1*weFF698N91q7xd1VdC01uw.jpeg"><div class="crosshair u-ignoreBlock"></div></div><br/><figcaption class="imageCaption" contenteditable="true" data-default-value="Type caption for image (optional)">In today’s world, location accuracy is paramount</figcaption></figure><p name="1d0f" class="graf graf--p graf-after--figure">This plugin allows an app to request a specific accuracy for Location Services. If the requested accuracy is higher than the current Location Mode setting of the device, the user is asked to confirm the change with a Yes/No dialog.</p><p name="3efa" class="graf graf--p graf-after--p">For example, if a navigation app that requires GPS, the plugin is able to switch on Location Services or change the Location Mode from low accuracy to high accuracy, without the user needing to leave the app to do this manually on the Location Settings page.</p><p name="3185" class="graf graf--p graf-after--p">More accuracy, less errors. No more turning on wrong turns</p><figure tabindex="0" contenteditable="false" name="6ed2" class="graf graf--figure graf-after--p"><div class="aspectRatioPlaceholder is-locked" style="max-width: 480px; max-height: 270px;"><div class="aspectRatioPlaceholder-fill" style="padding-bottom: 56.3%;"></div><img class="graf-image" data-image-id="1*Lnq0jaYRKRVf2nfNBVtDZA.gif" data-width="480" data-height="270" src="https://cdn-images-1.medium.com/max/720/1*Lnq0jaYRKRVf2nfNBVtDZA.gif"><div class="crosshair u-ignoreBlock"></div></div><br/><figcaption class="imageCaption" contenteditable="true" data-default-value="Type caption for image (optional)">Turn left at&nbsp;.. the&nbsp;..&nbsp;what</figcaption></figure><p name="fa88" class="graf graf--p graf-after--figure"><strong class="markup--strong markup--p-strong">IMPORTANT</strong>: This plugin depends on the Google Play Services library, so you must install the “Google Repository” package under the “Extras” section in Android SDK Manager. Otherwise the build will fail.</p><p name="da62" class="graf graf--p graf-after--p">To install the plugin use</p><pre name="2d13" class="graf graf--pre graf-after--p">ionic cordova plugin add cordova-plugin-request-location-accuracy</pre><pre name="8fbc" class="graf graf--pre graf-after--pre">npm install @ionic-native/location-accuracy</pre><p name="33d4" class="graf graf--p graf-after--pre">Import the plugin in a component with</p><pre name="86fc" class="graf graf--pre graf-after--p"><code class="markup--code markup--pre-code">import { LocationAccuracy } from '@ionic-native/location-accuracy/ngx';<br><br>constructor(private locationAccuracy: LocationAccuracy) { }</code></pre><p name="38ef" class="graf graf--p graf-after--pre">Then start using the plugin</p><pre name="ed01" class="graf graf--pre graf-after--p"><code class="markup--code markup--pre-code">this.locationAccuracy.canRequest().then((canRequest: boolean) =&gt; {<br><br>  if(canRequest) {<br>    // the accuracy option will be ignored by iOS<br>    this.locationAccuracy.request(this.locationAccuracy.REQUEST_PRIORITY_HIGH_ACCURACY).then(<br>      () =&gt; console.log('Request successful'),<br>      error =&gt; console.log('Error requesting location permissions', error)<br>    );<br>  }<br><br>});</code></pre><h3 name="4f9c" class="graf graf--h3 graf-after--pre">Conclusion</h3><p name="3090" class="graf graf--p graf-after--h3">In this post, we learnt about several different plugins that can be used for location related features in our apps. Some of these are far-field (GPS), while some are near-field sensor plugins. You can use these plugins for a variety of purposes from tracking your location, to sending relevant data to nearby customers and requesting accurate location.</p><p name="1720" class="graf graf--p graf-after--p">Stay tuned for more Ionic 4 blogs&nbsp;!</p><h3 name="97a7" class="graf graf--h3 graf-after--p">FOUND THIS POST INTERESTING&nbsp;?</h3><p name="95a9" class="graf graf--p graf-after--h3">Also check out our other blog posts related to <a href="https://medium.com/enappd/how-to-use-firebase-with-ionic-4-complete-guide-for-beginners-1888b1034024"  class="markup--anchor markup--p-anchor"    target="_blank">Firebase in Ionic 4</a>, <a href="https://medium.com/enappd/using-geolocation-and-beacon-plugins-in-ionic-4-754b41304007"  class="markup--anchor markup--p-anchor"    target="_blank">Geolocation</a> in Ionic 4, <a href="https://medium.com/enappd/qr-code-scanning-and-optical-character-recognition-ocr-in-ionic-4-95fd46be91dd"  class="markup--anchor markup--p-anchor"    target="_blank">QR Code and scanners</a> in Ionic 4 and <a href="https://medium.com/enappd/payment-solutions-in-ionic-8c4bb28ce5cc"  class="markup--anchor markup--p-anchor"    target="_blank">Payment gateways in Ionic 4</a></p><p name="ed14" class="graf graf--p graf-after--p">Also check out this interesting post on <a href="https://medium.com/enappd/how-to-create-mobile-games-pwa-with-ionic4-and-phaser-7fb1e917678e"  class="markup--anchor markup--p-anchor"    target="_blank">How to create games in Ionic 4 with Phaser</a></p><h3 name="362a" class="graf graf--h3 graf-after--p">NEED FREE IONIC 4 STARTERS?</h3><p name="eff2" class="graf graf--p graf-after--h3">You can also find free Ionic 4 starters on our website <a href="http://enappd.com"  class="markup--anchor markup--p-anchor" rel="noopener"    target="_blank">enappd.com</a></p><ul class="postList"><li name="2b12" class="graf graf--li graf-after--p"><a href="https://store.enappd.com/product/free-chat-themes-ionic4/"  class="markup--anchor markup--li-anchor" rel="noopener"    target="_blank">Free Chat Themes Starter for Ionic 4</a></li><li name="a4be" class="graf graf--li graf-after--li"><a href="https://store.enappd.com/product/ionic4-firebase-starter/"  class="markup--anchor markup--li-anchor" rel="noopener"    target="_blank">Free Ionic 4&#8202;—&#8202;Firebase Starter</a></li></ul><p name="2930" class="graf graf--p graf-after--li">You can also make your next awesome app using <a href="https://store.enappd.com/product/ionic-4-full-app/"  class="markup--anchor markup--p-anchor" rel="noopener"    target="_blank">Ionic 4 Full App</a></p><h3 name="1b1c" class="graf graf--h3 graf-after--p">References</h3><ul class="postList"><li name="bb4a" class="graf graf--li graf-after--h3 graf--trailing"><a href="https://ionicframework.com/docs"  class="markup--anchor markup--li-anchor" rel="noopener"    target="_blank">Ionic documentation</a></li></ul></div></div></section><section name="56cd" class="section section--body section--last"><div class="section-divider"><hr class="section-divider"></div><div class="section-content"><div class="section-inner sectionLayout--insetColumn"><p name="3cfa" class="graf graf--p graf--leading graf--trailing"><em class="markup--em markup--p-em">This blog was originally published on </em><a href="https://enappd.com/blog/"  class="markup--anchor markup--p-anchor" rel="noopener"    target="_blank"><em class="markup--em markup--p-em">Enappd</em></a><em class="markup--em markup--p-em">.</em></p></div></div></section></div></article></main>