点击时删除 GMSMarker

Remove GMSMarker when tapped

如何在点击时删除 GMSMarker?我希望当点击标记时,警报控制器会出现并询问用户是要保存还是删除点击的标记。那么,当按下 'remove' 按钮时,如何删除点击的标记呢?以及如果按下 'save' 之后用户访问地图时如何保存它。到目前为止我有这个基本结构但不确定如何实现功能:

  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
}

那么我该去哪里呢?任何建议,将不胜感激。

只需将地图设置为零,标记就会消失。

marker.map = nil

要从地图中删除标记,请将 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 上的地图上显示保存的标记,首先检索保存的经度和纬度:

let latitude = UserDefaults.standard.double(forKey: "lat")
let longitude = UserDefaults.standard.double(forKey: "lon")

并使用这些值构造一个新的GMSMarker

如果你想在地图上保存多个标记,你需要使用Core Data。这比 UserDefaults 更棘手一点。我建议你先阅读一些教程。然后,您可以阅读我所做的类似项目的代码 - LongLatMap.