ТОЛЬКО показывать аннотации для мест в радиусе

Я пытаюсь показать только аннотации для мест, ближайших к моему пользователю. У меня уже есть все местоположения, сохраненные в firebase, и сейчас я просто пытаюсь получить их и заполнить Map и TableView только местоположениями вокруг пользователя. Я пробовал GeoFire и несколько других, но я уверен, что я делаю это неправильно. Может ли кто-нибудь помочь?

Настройка БД

  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()
            })
        }

Вот как я настроил свой стол:

func tableView (_ tableView: UITableView, раздел numberOfRowsInSection: 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)
}

1 ответ

Решение

Как потому что мое местоположение отличается от вашего местоположения. Я проверил это на устройстве, и результат был как расстояние от моего местоположения, и ваше место встречи было большим приблизительно 3K . так что вы можете использовать этот файл кода и проверить его на вашем устройстве, это поможет.

1) Я заменил вашу функцию didload на данный момент как другую функцию и вызвал ее в DidUpdateLocation of maps

2) использовал //iosGeek в качестве комментария над строками кода, куда я вставил код в файл.

3) пока я не заполняю данные на карте или в таблице из-за разницы в местоположении

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

Посмотрите на эту функцию в вашем FeedVc

1) Пожалуйста, проверьте его на устройстве, чтобы получить разницу в местоположении

2) Распечатайте местоположение в консоли, чтобы проверить, сбывается ли оно

3) напечатайте self.postdata в условии If else, чтобы проверить, что поступает в качестве вывода

    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)")
                }

            }
        }
    }

Комментарий, если проблема все еще возникает

Другие вопросы по тегам