2017-04-15 3 views
0

私はUILongPressGestureRecognizerでマーカーを追加したいが、私のコードはうまくいかなかった。この方法はあまりにも動作しますしないUILongPressGestureRecognizerでGoogleマップにマーカーを追加するswift3

func setupGesture() { 
     let longPressRecognizer = UILongPressGestureRecognizer(target: self, action: #selector(action)) 
     longPressRecognizer.minimumPressDuration = 1.0 
     mapView.addGestureRecognizer(longPressRecognizer) 
    } 

    func action(recognizer: UILongPressGestureRecognizer) { 
     if (recognizer.state == .ended) { 
      DispatchQueue.main.async { 
       let longPressPoint = recognizer.location(in: mapView) 
       let coordinate = self.mapView.projection.coordinate(for: longPressPoint) 
       let marker = GMSMarker(position: coordinate) 
       marker.title = "Hello World" 
       marker.map = mapView 
      } 
     } 
    } 

..

extension MapViewController: GMSMapViewDelegate { 
    func mapView(_ mapView: GMSMapView, didLongPressAt coordinate: CLLocationCoordinate2D) { 
     DispatchQueue.main.async { 
      let marker = GMSMarker(position: coordinate) 
      marker.title = "Hello World" 
      marker.map = mapView 
     } 
    } 
} 
+0

didLongTapAtデリゲートの機能を使用し、 'DispatchQueue.main.async {//あなたのマーカーcode' –

+0

はい、私はメインスレッドでそれをしましたが、マーカーは表示されません –

答えて

1

このコードは、私のために完全に正常に動作します。あなたがUILongTapGestureRecogniserを必要としない、ただのMapViewのデリゲートを設定し、あなたがメインスレッドであなたのUIを更新してください

class ViewController: UIViewController { 

    var mapView: GMSMapView! 

    override func viewDidLoad() { 
     super.viewDidLoad() 
     // Do any additional setup after loading the view, typically from a nib. 

     self.mapView.delegate = self 
    } 

    override func loadView() { 
     // Create a GMSCameraPosition that tells the map to display the 
     // coordinate -33.86,151.20 at zoom level 6. 
     let camera = GMSCameraPosition.camera(withLatitude: -33.86, longitude: 151.20, zoom: 6.0) 
     self.mapView = GMSMapView.map(withFrame: CGRect.zero, camera: camera) 
     view = mapView 

     // Creates a marker in the center of the map. 
     let marker = GMSMarker() 
     marker.position = CLLocationCoordinate2D(latitude: -33.86, longitude: 151.20) 
     marker.title = "Sydney" 
     marker.snippet = "Australia" 
     marker.map = mapView 
    } 
} 

extension ViewController: GMSMapViewDelegate { 
    func mapView(_ mapView: GMSMapView, didLongPressAt coordinate: CLLocationCoordinate2D) { 
     let marker = GMSMarker() 
     marker.position = coordinate 
     marker.title = "" 
     marker.snippet = "" 
     marker.map = mapView 
    } 
} 
+0

コードを共有していただき、ありがとうございます。セットアップMapView.delegate = Self in ViewDidLoad –

関連する問題