GeoFire geoQuery.on()将返回的值存储到数组中以供后者使用

时间:2015-08-03 21:38:14

标签: angularjs firebase geofire

我在Ionic Framework中使用Geo Fire和Angular JS这里是我的Geo Fire Code看起来像

geoQuery = geoFire.query({
 center: [location.lat, location.lng],
 radius: 5
});

geoQuery.on("key_entered", function(key, location, distance){//something here})

在这里,我得到所有匹配的信息,我需要这三个变量分别是key,location&距离。在这种情况下,我的查询匹配来自firebase的3个信息。现在我想使用ng-repeat将信息显示到离子列表中。为此,我使用以下代码将这些信息保存到数组中。

var hello = geoQuery.on("key_entered", function(key, location, distance) {
  var names = [];
  names.push(key);
  distance = distance.toFixed(2);
  var distances = [];
  distances.push(distance);
});

但我的列表只显示信息中的最后一个值。在这里,我拍摄了控制台的屏幕截图。在这里,我们可以看到与我的查询匹配的这3个距离值。 但是列表只显示最后一个值。 here we can see the 3 values of distance

1 个答案:

答案 0 :(得分:4)

让我们分析您的代码,看看我们是否可以解释您看到的行为:

var hello = geoQuery.on("key_entered", function(key, location, distance) {
  var names = [];
  names.push(key);
  distance = distance.toFixed(2);
  var distances = [];
  distances.push(distance);
});

每次键进入查询标识的区域时,都会执行回调函数。在该函数中,您将创建两个数组并添加键和距离。因此,对于每个键,您创建两个新数组,可能不是您想到的。

试试这样:

var names = [];
var distances = [];
var hello = geoQuery.on("key_entered", function(key, location, distance) {
  names.push(key);
  distance = distance.toFixed(2);
  distances.push(distance);
});

现在每次键进入区域时,都会添加键和距离到现有数组。因此,随着时间的推移,您将在该阵列中获得大量的键和距离。

请注意,当key_exited事件触发时,您还应删除其数组中的键+距离。