ios - 点击时删除 GMSMarker

标签 ios swift google-maps google-maps-markers uialertcontroller

如何在点击时删除 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/

相关文章:

ios - WKWebView 在加载另一个 URL 时不会重新呈现内容

ios - Firebase 观察者事件类型

ios - 使用 UICollectionView 的过渡传递数据

javascript - 如何同时通过多个请求将数据从 php 传递到 javascript

angular - 未知 "google is not defined"Angular 6 中的 Google map 集成

javascript - safari 无法打开页面,因为服务器停止响应

ios - UIButton 作为复杂 UIScrollView 上的 subview

ios - 来自 NSURL 的 Swift PHAsset

macos - macOS 应用程序中还需要 Swift 的嵌入式 dylib吗?

json - 使用按钮更新用户位置并快速绘制路线