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

React Native Cli集成geofirestore遇TypeError问题求助

解决GeoFirestore的TypeError问题

错误原因

出现GeoFirestore.collection is not a function的核心问题:

  • 直接调用GeoFirestore类的collection方法,但该方法属于实例对象而非类本身
  • Firebase v9模块化版本中,GeoPoint的调用方式错误
  • 自定义变量query与Firebase导入的query重名,引发冲突

修复步骤及代码修改

1. 调整实现文件的导入逻辑

删除实现文件中单独导入的GeoFirestore,改为导入配置文件中已实例化好的geofirestore对象;同时导入Firebase的GeoPoint。

2. 修正集合获取与地理查询代码

使用实例化的geofirestore调用collection,修正GeoPoint创建方式,避免变量名冲突。

修改后的实现文件代码:

import { useNavigation } from "@react-navigation/native";
import { useEffect, useState } from "react";
import GetLocation from 'react-native-get-location'
import { collection, onSnapshot, orderBy, query, where, getDocs, GeoPoint } from "firebase/firestore"; // 新增GeoPoint导入
import { db, geofirestore } from "../../utils/keys" // 导入配置好的geofirestore实例
import { getAuth } from "firebase/auth";

const obtenerRegistrosCercanos = async () => {
    // 使用实例化的geofirestore获取集合
    const eventosCollection = geofirestore.collection('eventos');
    
    // 用导入的GeoPoint创建地理坐标
    const center = new GeoPoint(19.325471, -99.656188);

    const radius = 10;

    // 避免变量名冲突,将query改为geoQuery
    const geoQuery = eventosCollection.near({
        center,
        radius,
      });

      geoQuery.get().then((snapshot) => {
        snapshot.docs.forEach((doc) => {
          const data = doc.data();
          console.log(data);
        });
      });     
  };

3. 确认配置文件的正确性

你的配置文件已正确实例化GeoFirestore,无需修改,保持如下即可:

import { initializeApp } from 'firebase/app';
import { getAuth } from 'firebase/auth';
import { getFirestore } from 'firebase/firestore';

import { GeoFirestore } from 'geofirestore';

const firebaseConfig = {
  // 你的配置信息
};


const app = initializeApp(firebaseConfig);
const authentication = getAuth(app);
const db = getFirestore(app);

const geofirestore = new GeoFirestore(db);

export { app, authentication, db,  geofirestore };

额外注意事项

  • 确保eventos集合中的文档包含地理坐标字段(默认是geopoint,若自定义字段名,需在near方法中指定field参数)
  • 地理查询需要Firestore索引支持,若运行后出现索引错误,按照控制台提示创建对应地理索引

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.06.26 21:59:56