2016-10-11 16 views
1

Firebaseを使用して注釈をmapViewに取得しています。これは、以下を介して行われます。注釈座標を使用して注釈を削除する

func getMarkers() { 

    dbRef.observe(.value, with: { (snapshot) in 

     for buildings in snapshot.children { 

      let buildingsObject = Buildings (snapshot: buildings as! FIRDataSnapshot) 

      let latDouble = Double(buildingsObject.latitude!) 
      let lonDouble = Double(buildingsObject.longitude!) 

      self.telephoneNumber = buildingsObject.number 

      let annotation = myAnnotationView.init(title: buildingsObject.content!, coordinate: CLLocationCoordinate2D.init(latitude: latDouble!, longitude: lonDouble!), duration: buildingsObject.duration!, cost: buildingsObject.cost!, info: "", timestamp: buildingsObject.timestamp, contactNumber: buildingsObject.number!, addedBy: buildingsObject.addedByUser!) 

      self.mapView.addAnnotation(annotation) 

      print (snapshot) 

     }})} 

myAnnotationViewは、AnnotationViewのカスタムクラスです。
地図に注釈を追加しても問題ありません。この問題は、ユーザーが注釈を削除する必要がある場合、その注釈をmapViewから削除する必要があります。私はすべてのユーザーの注釈を含む表を持っています。これでFirebaseコンソールが更新され、データは削除されます。ただし、アノテーションはマップ上に残ります。アプリをリセットするとアノテーションが更新されます。

正しいスナップショットを取得したdeletedChildsを監視する方法がありますが、削除する必要がある注釈を参照しているようです。

func removeMarkers() { 

    dbRef.observe(.childRemoved, with: { (snapshot) in 

         print (snapshot) 

    })} 

吐き出しされているスナップショットはここにある:

Snap (-KTo3kdGGA_-rfUhHVnK) { //childByAutoID 
    addedByUser = TzDyIOXukcVYFr8HEBC5Y9KeOyJ2; 
    content = "Post"; 
    cost = 500; 
    duration = Monthly; 
    latitude = "25.0879112000924"; 
    longitude = "55.1467777484226"; 
    number = 1234567890; 
    timestamp = "Tue 11 Oct"; 
} 

だから私の質問は、どのように私は、このスナップショットにある注釈を削除することができますか?どういうわけかその座標を参照して、そのようにアノテーションを削除できますか?私はStackを見てきましたが、主にすべての注釈を削除する方法について言及しています。

多くのありがとうございます。 D

答えて

3

MapKitにはremoveAnnotationメソッドがあり、これを使用して特定の注釈を削除できます。

あなたの場合、座標を比較する方法が必要です。 WEはCLLocationCoordinate2D

extension CLLocationCoordinate2D: Hashable { 
    public var hashValue: Int { 
     get { 
      // Add the hash value of lat and long, taking care of overlfolow. Here we are muliplying by an aribtrary number. Just in case. 
      let latHash = latitude.hashValue&*123 
      let longHash = longitude.hashValue 
      return latHash &+ longHash 
     } 
    } 
} 

// Conform to the Equatable protocol. 
public func ==(lhs: CLLocationCoordinate2D, rhs: CLLocationCoordinate2D) -> Bool { 
    return lhs.latitude == rhs.latitude && lhs.longitude == rhs.longitude 
} 

の拡張子を使用すると、今、あなたはあなたの座標&任意のマッチはそれを削除するかどうかを確認することができ、マップからすべての注釈を取得できることを行うことができます。

 let allAnnotations = self.mapView.annotations 
     for eachAnnot in allAnnotations{ 
      if eachAnnot.coordinate == <Your Coordinate>{ 
       self.mapView.removeAnnotation(eachAnnot) 
      } 
     } 
+0

完全に作業しました。これは決して考えなかったでしょう。多くのありがとう@TheAppMentor –

+0

@TheAppMentorに感謝します。私は私の特定のコードの解決策を探しており、これはうまく機能します。 –

関連する問題