如何在点击时删除 GMSMarker?我希望当点击标记时出现一个警报 Controller ,并询问用户是否要保存或删除点击的标记。那么,当按下“删除”按钮时,如何删除点击的标记呢?以及如果按下“保存”按钮,当用户稍后访问 map 时如何保存它。到目前为止我已经有了这个基本结构,但不确定如何实现该功能:
func mapView(_ mapView: GMSMapView, didTap marker: GMSMarker) -> Bool {
print("didtapmarker")
let alert = UIAlertController(title: "Add this place to wishlist?",
message: "Would you like to add this to your list?",
preferredStyle: .alert)
let saveAction = UIAlertAction(title: "Save",
style: .default)
let cancelAction = UIAlertAction(title: "Remove",
style: .default)
//alert.addAction(defaultAction)
alert.addAction(saveAction)
alert.addAction(cancelAction)
self.present(alert, animated: true, completion: nil)
return false
}
那么我该去哪里呢?任何建议,将不胜感激。
最佳答案
要从 map 中删除标记,请将 map
设置为 nil
:
marker.map = nil
您可以在初始化UIAlertAction
时将上述代码放入handler
闭包中:
let cancelAction = UIAlertAction(title: "Remove",
style: .default) {
_ in marker.map = nil
}
保存标记有点复杂。如果您一次只想保存一个标记,可以使用 UserDefaults
。
if let latitude = marker.latitude?.doubleValue, let longitude = marker.longitude?.doubleValue {
UserDefaults.standard.set(latitude, forKey: "lat")
UserDefaults.standard.set(longitude, forKey: "lon")
}
要在 viewDidLoad
上的 map 上显示保存的标记,请首先检索保存的经度和纬度:
let latitude = UserDefaults.standard.double(forKey: "lat")
let longitude = UserDefaults.standard.double(forKey: "lon")
并使用这些值构建新的 GMSMarker
。
如果要在 map 上保存多个标记,则需要使用 Core Data。这比 UserDefaults 稍微棘手一些。我建议您先阅读一些教程。然后,您可以阅读我所做的类似项目的代码 - LongLatMap .
关于ios - 点击时删除 GMSMarker,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/41292694/