Search code examples
ionic-frameworkibeaconionic-nativeproximity

How to get the closest beaon in Ionic 3


currently I’m working with iBeacons and by far have managed to scan and display them on screen. But then I was told to scan and display for ONLY the nearest one ( the closest one), and ignore all the others. Can someone give me a rough idea how to get the closest beacon among a bunch of beacons that I have?

I believe that I can’t use the Proximity and Accuracy in this case since they often fluctuate.

Basically I haven't figured out how to work with the logic:

onBeaconsDiscovered() {
    this.delegate.didRangeBeaconsInRegion().subscribe( data => {

      if (data.beacons !== null) {
        let nearestBeacon = // { code for detecting the nearest beacon }

        // then show up a notification / alert / toast ...
      }
    });

  }

Please help! I appreciate every idea.


Solution

  • You can see my answer on how to do this in native Swift code here : Swift find closest Beacon by rssi

    Here is a direct translation of that Swift code into JavaScript:

     var closestBeacon = null;
     for (var beacon in data.beacons) {
       if (beacon.rssi < 0 && closestBeacon != null && beacon.rssi > closestBeacon.rssi) {
         closestBeacon = beacon;
       }
     }
    

    Keep in mind that the this.delegate.didRangeBeaconsInRegion().subscribe( data => { callback will happen once per second. So if you want to issue an alert based upon the closest beacon, you also need to take care not to to pop up new alerts every single second.

    If you want to keep track of beacons you have already handled, you can declare a new object in some global-like scope outside the callback:

      var triggeredBeacons = {};
    

    Then before you do any processing on a beacon, construct a string key based on your beacon identifiers, and make sure it has not triggered before:

      var beaconIdentifiers = beacon.uuid + " " + beacon.major + " " + beacon.minor;
      if (triggeredBeacons[beaconIdentifiers] == true) {
        // beacon has already triggered.  Ignore it
      }
      else {
        triggeredBeacons[beaconIdentifiers] = true;
        // Put your beacon processing here
      }