我正在使用 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 自定义的类。
向 map 添加注释没问题。如果用户需要删除他的注释,那么问题就出现了,它需要从 mapView 中删除。我有一个包含所有用户注释的表格,如果他们愿意,他可以在其中删除。这会更新到 firebase 控制台并删除数据。但是,注释仍在 map 上,只有当您重置应用程序时,注释才会更新。
我有一种方法可以观察 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,但它主要提到了如何删除所有注释。
非常感谢。
最佳答案
MapKit 有 removeAnnotation 方法,可以用来删除特定的注释。
在您的情况下,您需要一种比较坐标的方法。我们可以使用 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
}
现在,您可以从 map 中获取所有注释,可以检查是否有匹配您的坐标并将其删除。
let allAnnotations = self.mapView.annotations
for eachAnnot in allAnnotations{
if eachAnnot.coordinate == <Your Coordinate>{
self.mapView.removeAnnotation(eachAnnot)
}
}
关于ios - 使用注释坐标删除注释,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/39980004/