How to get nearby queries / restaurants from firestore using react native (GeoFirestore)

724 Views Asked by At

So i'm trying to get retrieve nearby restaurents based on user location. I'm using Geofirestore library to attempt to query nearby restaurent but with no luck. It just creates a document with fields like geohash,lat,long and store. and when i console log the nearby query i get an empty array? Code is below

  export default () => {
  const [restaurantsList, setRestaurantsList] = useState([]); //Initialise restaurant list with setter
  const [errorMessage, setErrorMessage] = useState("");
  const [lat, setLat] = useState(0);
  const [lng, setLng] = useState(0);
  const[nearbyLocations, setnearbyLocations] = useState(null);
  
  //const type = route.params.('type', 'anonymous')

  console.log(restaurantsList)
  console.log(lat, lng)
  console.log(nearbyLocations)
// // Initialize the Firebase SDK
// firebase.initializeApp({
//   // ...
// });


const getUserLocation = () => {
  if (navigator.geolocation) {
    navigator.geolocation.getCurrentPosition((position) => {
      setLat(position.coords.latitude);
      setLng(position.coords.longitude);
    });
  }
}

  const getNearbyRestaurents = () => {
  //Create a Firestore reference
  const firestore = firebase.firestore();

  // Create a GeoFirestore reference
  const GeoFirestore = geofirestore.initializeApp(firestore);

  // Create a GeoCollection reference
  // Firebase reference where GeoFirestore will store its information
  const geocollection = GeoFirestore.collection('user_location');

  //Add a GeoDocument to a GeoCollection
  geocollection.add({
    name: 'Geofirestore',
    score: 100,
    // The coordinates field must be a GeoPoint!
    coordinates: new firebase.firestore.GeoPoint(lat, lng)
  })

  // Create a GeoQuery based on a location
  const query = geocollection.near({ center: new firebase.firestore.GeoPoint(lat, lng), radius: 20 });

  // Get query (as Promise)
  query.get().then((value) => {
    // All GeoDocument returned by GeoQuery, like the GeoDocument added above
    console.log(value.docs);
    setnearbyLocations(value.docs)
  });
  }

    const getRestaurants = async () => {
      try {
        const list = [];
        var snapshot = await firebase.firestore().collection("Restaurants").get(); // gets data from the restaurents table
        console.log("Here");
        snapshot.forEach((doc) => { // iterates through each document in the table and push
          list.push(doc.data());
        });
        setRestaurantsList([...list]);;
      } catch (e) {
        setErrorMessage(
          "There's nae bleeding restaurants, I told you to upload them!"
        );
      }
    };

  //Call when component is rendered
  useEffect(() => {
    getRestaurants();
  }, []);

So My goal is to return all nearby restaurents based on users locations. I have two fields called 'Latitude' and 'Longitude' in each restaurent collections

0

There are 0 best solutions below