Skip to content
Advertisement

Get GeoFire to return null if there is no index within radius zone

I am building a webapp with angularjs and am using firebase. I am using geofire to return values that are within a given radius of a given lat, lng. It s fully working and returns what I want when there are values in the radius. However, when there are no values in the radius zone it returns nothing. This is a problem because on initial page load I have a spinner that starts and ends when something is returned in a promise. Is there a way to have geofire return a null value if there are no values in the given radius?

This is the code I am using to retrieve the data:

geoQuery.on("key_entered", function(key, location, distance) {
        console.log(key + " entered query at " + location + " (" + distance + " km from center)");


  console.log(key);

      },function(error) {
        console.log("Promise was rejected with the following error: " + error);
      });
    });

The console.log will not run unless something is found that is in the radius zone. I need it to still return something so I know to alert the user there are no businesses in the given area. Any help would be greatly appreciated!

UPDATE:

I added the ‘ready’ event as well thinking it would trigger the ‘key_entered’ event but it did not thus leaving me back at square one.

var onKeyExitedRegistration = geoQuery.on("key_exited", function(key, location, distance) {

console.log(key + ” exited query to ” + location + ” (” + distance + ” km from center)”); });

geoQuery.on("ready",function() {
  console.log(key + " moved within query to " + location + " (" + distance + " km from center)");

});

Advertisement

Answer

The key_entered event will only fire when a key enters the geo-query. So if no key ever enters the query it will never fire.

To check if any keys initially are in the geo-query, you can listen for the ready event. This fires after the initial data has loaded, so:

var keysEntered = false;
geoQuery.on("key_entered", function(key, location, distance) {
    console.log(key + " entered query at " + location + " (" + distance + " km from center)");
    keysEntered = true;
  },function(error) {
    console.log("Promise was rejected with the following error: " + error);
  });
});
geoQuery.on("ready", function() {
  console.log("initial data has loaded");
  if (!keysEntered) {
    console.log("There was no initial data, so there are no business in range (yet).");
  }
});

See the API reference of Geofire for JavaScript for more information.

Advertisement