You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

如何将GeoFire商家位置数据存入Firebase实时数据库BusLocations集合

问题:将GeoFire位置数据存入Firebase实时数据库指定节点(BusLocations)

我正在为商家添加GeoFire位置信息,当前代码会把数据存入随机生成的节点,希望改为存入BusLocations节点。

当前实现代码

var firebaseRef = push(ref(getDatabase()));
var geoFireInstance = new geofire.GeoFire(firebaseRef); 

geoFireInstance.set(newUserName.value, [ lat2, lon2 ]).then(function() {
        console.log("Provided key has been added to GeoFire: ");
}, function(error) {
     console.log("Error: " + error);
});  

当前存储结构(随机节点)

{
  "-NiaHRxzh28S4UIMXa3E": { // 随机生成节点
    "STEAKSHAKE": {
      ".priority": "9yzekk35e8",
      "g": "9yzekk35e8",
      "l": [
        38.5639904,
        -90.5148296
      ]
    }
  },
  "-NiaN_K_KgBL95hq-0oz": { // 随机生成节点
    "B": {
      ".priority": "9yzemjne3j",
      "g": "9yzemjne3j",
      "l": [
        38.5680936,
        -90.4744243
      ]
    }
  }
}

期望存储结构(存入BusLocations)

{
  "BusLocations": { // 目标节点
    "HARDEES67890": {
      "g": "9yzej7tx7n",
      "l": [
        38.5166,
        -90.46473
      ]
    },
    "LAZYRIVERBALLWIN": {
      "g": "9yzekjhp9b",
      "l": [
       "38.5687933",
        "-90.5217678"
      ]
    }
  }
}

解决方案

问题出在push(ref(getDatabase()))会自动生成随机节点,只需将Firebase引用直接指向BusLocations路径即可:

修改后的代码

// 直接指向BusLocations节点,而非生成随机节点
var firebaseRef = ref(getDatabase(), 'BusLocations');
var geoFireInstance = new geofire.GeoFire(firebaseRef); 

geoFireInstance.set(newUserName.value, [ lat2, lon2 ]).then(function() {
        console.log("商家位置已成功存入BusLocations节点");
}, function(error) {
     console.log("存储失败:" + error);
});  

说明

  • 去掉push()方法,直接用ref(getDatabase(), 'BusLocations')获取指定节点的引用
  • GeoFire实例会将商家的位置数据直接写入BusLocations节点下,以商家名称(newUserName.value)作为键,结构与期望一致

内容的提问来源于stack exchange,提问作者user22407520

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.07.07 02:05:14