在Google Maps Swift中,当用户触摸屏幕时放置一个标记。

3

我想在谷歌地图中添加和删除标记(pin)。

我想通过长按来放置标记并将其删除。我想用它来选择我的目的地。我该如何做?

let  position = CLLocationCoordinate2DMake(10, 10)
let marker = GMSMarker(position: position)
marker.map = mapView
2个回答

6

如果您正在寻找一个完整的使用Swift的代码片段:

  1. 实现协议 GMSMapViewDelegate
  2. 拖动 GMSMapView 的实例 @IBOutlet weak var googleMapView: GMSMapView!
  3. viewDidLoad() 中提及 GMSMapView 委托,如下 googleMapView.delegate = self
  4. 实现 didTapAt 委托函数:

func mapView(_ mapView: GMSMapView, didTapAt coordinate: CLLocationCoordinate2D){ print("You tapped at \(coordinate.latitude), \(coordinate.longitude)") googleMapView.clear() // 在添加新位置之前清除标记 let marker = GMSMarker(position: coordinate) marker.map = googleMapView }


4
这段代码应该能帮到你!
//MARK: GMSMapViewDelegate Implimentation.
func mapView(_ mapView: GMSMapView, didTapAt coordinate: CLLocationCoordinate2D) {
    plotMarker(AtCoordinate: coordinate, onMapView: mapView)
}

//MARK: Plot Marker Helper
private func plotMarker(AtCoordinate coordinate : CLLocationCoordinate2D, onMapView vwMap : GMSMapView) {
    let marker = GMSMarker(position: coordinate)
    marker.map = vwMap
}

PS:别忘了在ViewController中确认GMSMapViewDelegate并在viewDidLoad()中的某处分配googleMap.delegate = self

希望这可以帮到你!


网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接