将动作点击分配给 google 地图标记,swift 2

Assign action tap to google map marker, swift 2

我有一个 google 地图标记,我希望当我点击标记时将我发送到另一个 viewController,或者在我的地图上显示一个按钮,

let marker1 = GMSMarker()
marker1.position = CLLocationCoordinate2DMake(24.8236423, -107.4234671)
marker1.appearAnimation = kGMSMarkerAnimationPop
marker1.icon = UIImage(named: "flag_icon")
marker1.title = "Any title"
marker1.snippet = "Any text"
marker1.map = mapView

我解决了,这是tap函数

    //Market Tap Function
func mapView(mapView: GMSMapView!, didTapMarker marker: GMSMarker!) -> Bool {
    let myFirstButton = UIButton()
    myFirstButton.setTitle("✸", forState: .Normal)
    myFirstButton.setTitleColor(UIColor.blueColor(), forState: .Normal)
    myFirstButton.frame = CGRectMake(15, -50, 300, 500)
    myFirstButton.addTarget(self, action: "pressed:", forControlEvents: .TouchUpInside)

    self.view.addSubview(myFirstButton)
    return true
}

您可以将这些步骤用于 swift 4 和 5

  1. 实施 GMSMapViewDelegate

  2. 像这样在 didviewload() 中将你的地图打到这个委托中:mygooglemap.delegate = self

  3. 将此功能添加到您的 class:

     func mapView(_ mapView: GMSMapView, didTap marker: GMSMarker) -> Bool {
     //do what ever you want
     return true
     }
    

对于Swift 5+

你可以使用 Delegete 方法做到这一点

  1. 将您的地图视图删除分配给自己

  2. 确认GMSMapViewDelegate你自己

这是代码

1

import UIKit
import GoogleMaps
import GooglePlaces

class HomeVC: UIViewController {
 
override func viewDidLoad() {
     super.viewDidLoad()
     self.mapView.delegate = self
  }

}

2

extension HomeVC:GMSMapViewDelegate {
    
    func mapView(_ mapView: GMSMapView, didTap marker: GMSMarker) -> Bool {
        print("Do what ever you want.")
        return true
    }
}