Brewski
Brewski

Reputation: 684

Load existing Geofire location if one exists

I would like Geofire to do one of two things; 1 - Look for a venue location in Firebase and if none exists, 2 - Create one.

So to clarify:

  1. User creates a post based on the current venue.
  2. Geofire checks to see if it already has a venue (Long and Lat cocoordinates) on record for that geolocation. If it DOES have that location stored in Firebase then it takes the user's new post and ADDS it to the same venue.
  3. If Geofire DOES NOT detect a location in Firebase it creates a new venue and attaches the post to it.

I have separated my venue details from my Geofire coordinates but I dont understand how do I get Geofire to differentiate between whether an entry for this location does or does not exist within Firebase.

At the moment when I run my app it creates a new entry every time as per the screen-grab below, which is obviously not what I want.

multiple entries with identical locations

Here is the code:

First I set the reference for the name and the directory (I set them seperately because I use the name ref in a few instances)

override func viewDidLoad() {
    super.viewDidLoad()

    geoFireNameRef = Database.database().reference().childByAutoId()
    geoFireRef = Database.database().reference().child("PostLocations").child("Coordinates")
    geoFire = GeoFire (firebaseRef: geoFireRef)
}

and then in my post method I call:

func savePost () {
     let location = CLLocation.init(latitude: lat!, longitude: long!) //Get Coordinates
     geoFire.setLocation(location, forKey: self.geoFireNameRef.key)// Save Coordinates 
postLocationDB.child(self.geoFireNameRef.key).setValue(locationDictionary) // Save Venue Details
}

Upvotes: 0

Views: 333

Answers (1)

Renaud Tarnec
Renaud Tarnec

Reputation: 83048

So I understand that you want to check if there is a venue with an existing couple of coordinates. What I would suggest is to store this couple under your Coordinates/{venueId} node as an extra field which is composed by the two coordinates, like the following:

- Coordinates
   - -LAWR2LH.....
     - l
        - 0: 22.345
        - 1: 22.345
     - compoundL: "22.345-22.345"

and then directly query the Real Time Database with a query that combines queryOrderedByChild and queryEqualToValue in order to find if a Coordinates/Venue node with compoundL = 22.345-22.345 is already existing.

Upvotes: 1

Related Questions