Search code examples
swiftfirebasemapkitmkannotationclcircleregion

ONLY Show annotations for venues within radius


I'm trying to only show the annotations for locations nearest to my user. I have all the locations already saved to firebase and now I'm just trying to retrieve them and populate the Map and TableView with only the locations around the user. I've tried GeoFire and a few others but, I'm sure I'm not doing this right. Could any one help?

Db setup

  override func viewDidLoad() {
            super.viewDidLoad()

            // Set up Map
            mapView.delegate = self
            mapView.userTrackingMode = MKUserTrackingMode.follow

            // Setup TableView
            tableView.delegate = self
            tableView.dataSource = self

            //Pulls TableData for UITableView
            DataService.ds.REF_VENUE.observe(.value, with: { (snapshot) in

                self.posts = [] // THIS IS THE NEW LINE

                if let snapshot = snapshot.children.allObjects as? [DataSnapshot] {
                    for snap in snapshot {
                        if let postDict = snap.value as? Dictionary<String, AnyObject> {
                            let key = snap.key
                            let post = Post(postKey: key, postData: postDict)
                            self.posts.append(post)
                        }

                        //Populates Map with annotations.
                    if let locationDict = snap.value as? Dictionary<String, AnyObject> {

                        let lat = locationDict["LATITUDE"] as! CLLocationDegrees
                        let long = locationDict["LONGITUDE"] as! CLLocationDegrees
                        let title = locationDict["NAME"] as! String
                        let center = CLLocationCoordinate2D(latitude: lat, longitude: long)
                        _ = MKCoordinateRegion(center: center, span: MKCoordinateSpan(latitudeDelta: 0.20, longitudeDelta: 0.20))

                        let annotation = MKPointAnnotation()
                        annotation.coordinate = CLLocationCoordinate2DMake(lat, long)
                        annotation.title = title.capitalized
                        self.mapView.addAnnotation(annotation)


                        }
                    }
                }
                self.tableView.reloadData()
            })
        }

Here is how I set up my table:

func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int { return posts.count }

func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {

    if let cell = tableView.dequeueReusableCell(withIdentifier: "detailCell", for: indexPath) as? PostCell {
    let cellData = posts[indexPath.row]

    cell.configureCell(post: cellData)
        return cell
    } else {
        return PostCell()
    }
}



func tableView(_ tableView: UITableView, didSelectRowAt indexPath: IndexPath) {
    let post = posts[indexPath.row]
    performSegue(withIdentifier: "previewSegue", sender: post)
}

Solution

  • As because my location is different from your location. I tested it on device and result was like distance from my location and your venue location was a large about 3K . so you can use that code file and check it in your device it will help.

    1) I had replaced your didload Function for now as a different func and calling it in DidUpdateLocation of maps

    2) used //iosGeek as a comment above lines of code where I inserted code in file.

    3) for now I am not populating data in map or table because of location difference

    Link: https://drive.google.com/open?id=0Bz8kF1Gedr7fNThTbTFZY1Q3LVk
    

    Have a look at this function in your FeedVc

    1) Please test it on a Device to get the location difference

    2) Print location in console to check if its coming true

    3) print self.postdata in If else condition to check what is coming as output

        if snapshot.exists(){
            if let snapshot = snapshot.children.allObjects as? [DataSnapshot] {
                for snap in snapshot {
    
                    //Here I just used your snapshot to filter data
                    self.postData = snap.value as! [String : AnyObject]
                    //calculating distance here with custom function made
                    let distance = self.calculateDistancxe(userlat: self.userLatt, userLon: self.userLonn, venueLat: self.postData["LATITUDE"]! as! CLLocationDegrees, venueLon: self.postData["LATITUDE"]! as! CLLocationDegrees)
                    //if Distance is less Than or equal to 2 km 
                    let aa : Int = Int(distance)!
                    if (aa <= 2){
    
                         //if yes , add *self.postData* in a new Dictionary or Array
    
                        print("*********\(self.postData)")
                        //time to use that postdata in a dict or array from which you will populate data in TableView
                    }
                    else{
                        //if condition don't satisfy
                        print("noting \(distance)")
                    }
    
                }
            }
        }
    

    Comment if still any issue occurs