Swift 3 如何在 Google 地图上触摸添加标记

3
我遇到了谷歌地图标记的问题,我想在触摸屏上放置标记,但我不知道如何处理它。我尝试了几种方法,但都没有效果,在我点击地图时什么也没发生。似乎是按压识别出现了问题。
class MainMapController: UIViewController, CLLocationManagerDelegate {

@IBOutlet weak var viewMap: GMSMapView!
var makers: [GMSMarker] = []

var locationManager = CLLocationManager()

override func viewDidLoad() {
    super.viewDidLoad()


    initializeTheLocationManager()
    self.viewMap.isMyLocationEnabled = true
  let longPressRecognizer = UILongPressGestureRecognizer(target: self, action: #selector(handleLongPress))
  self.viewMap.addGestureRecognizer(longPressRecognizer)


}

  func handleLongPress(recognizer: UILongPressGestureRecognizer)
   {
if (recognizer.state == UIGestureRecognizerState.began)
{
  let longPressPoint = recognizer.location(in: self.viewMap);
  let coordinate = viewMap.projection.coordinate(for: longPressPoint )
  let marker = GMSMarker(position: coordinate)
  marker.opacity = 0.6
  marker.title = "Current Location"
  marker.snippet = ""
  marker.map = viewMap
  makers.append(marker)
    }
  }


func initializeTheLocationManager()
{
    locationManager.delegate = self
    locationManager.requestWhenInUseAuthorization()
    locationManager.startUpdatingLocation()
}


func locationManager(_ manager: CLLocationManager,      didUpdateLocations locations: [CLLocation]) {

    var location = locationManager.location?.coordinate

    cameraMoveToLocation(toLocation: location)
    locationManager.stopUpdatingLocation()     
}    
func cameraMoveToLocation(toLocation: CLLocationCoordinate2D?) {
    if toLocation != nil {
        viewMap.camera = GMSCameraPosition.camera(withTarget: toLocation!, zoom: 15)        
    }
    }

viewMap 是一个 GMSMapView 吗? - Julien Kode
是的,你说得对。 - Egle Matutyte
当我点击地图时,什么也没有发生。 - Egle Matutyte
你能给我展示更多的代码吗? - Julien Kode
更新了我的问题。 - Egle Matutyte
@EgleMatutyte,你得到解决方案了吗? - Sagar Bhut
1个回答

9
您不应该手动添加手势识别器到Google Maps中,它会自己管理交互,并有专门的委托函数来处理常见手势。
要在GSMMapView上进行长按,请确保设置了委托。
self.mapView.delegate = self

然后连接适当的委托函数

extension ViewController: GMSMapViewDelegate {
    func mapView(_ mapView: GMSMapView, didLongPressAt coordinate: CLLocationCoordinate2D) {
         // Custom logic here
         let marker = GMSMarker()
         marker.position = coordinate
         marker.title = "I added this with a long tap"
         marker.snippet = ""
         marker.map = mapView
    }
}

上述代码将在您长按的位置添加一个标记,您还可以添加标题和片段,如您所见。实际将其添加到地图上的部分是marker.map = mapView


我尝试添加这个,但当我点击地图时没有任何反应。 - Egle Matutyte
你在长按吗?我这里有一个示例项目,其中包含这段代码,并且它对我来说运行良好。 - Scriptable
是的,我在这里,什么也没有发生,你能给我看一下吗? - Egle Matutyte
请查看此 Git 代码库。记得在 AppDelegate 中添加你的 API_KEY 才能运行。https://github.com/martinjkelly/gmaps-ios-long-tap-sample - Scriptable

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