DaBuIN / GitsTrap

"打不贏就進來吧" 卡關討論區
0 stars 1 forks source link

在MapView點擊取得地點座標並放大頭針 #11

Open Philoreiser opened 7 years ago

Philoreiser commented 7 years ago

這個是我們會用到的,先記錄起來:

https://stackoverflow.com/questions/34431459/ios-swift-how-to-add-pinpoint-to-map-on-touch-and-get-detailed-address-of-th

不要完全照他寫的打, 他的版本應該是Swift2。

Philoreiser commented 7 years ago

目前實作成功:

  1. 在mapView上單一點擊取得座標
  2. 取得座標插上大頭針

https://github.com/DaBuIN/TestDogsMap/blob/master/TestDogsMap/TestDogsMap/PickPlaceVC.swift

import UIKit import MapKit

class PickPlaceVC: UIViewController, MKMapViewDelegate {

@IBOutlet weak var navBar: UINavigationBar!
@IBOutlet weak var mapView: MKMapView!

@IBAction func back(sender: Any) {
    self.dismiss(animated: true, completion: nil)
}

override func viewDidLoad() {
    super.viewDidLoad()
    print("load pickPlaceVC")

    mapView.delegate = self

    let mapSingleTapReg = UITapGestureRecognizer(target: self, action: #selector(mapTapHandle) )
    mapSingleTapReg.delegate = self as? UIGestureRecognizerDelegate

    mapSingleTapReg.numberOfTapsRequired = 1
    mapSingleTapReg.numberOfTouchesRequired = 1

    let mapDoubleTapReg = UITapGestureRecognizer(target: self, action: nil)
    mapDoubleTapReg.delegate = self as? UIGestureRecognizerDelegate
    mapDoubleTapReg.numberOfTapsRequired = 2
    mapDoubleTapReg.numberOfTouchesRequired = 1

    // to distinguish single- and double-tap
    mapSingleTapReg.require(toFail: mapDoubleTapReg )

    // to make mapView recognizing single- and double-tap gestures
    mapView.addGestureRecognizer(mapSingleTapReg)
    mapView.addGestureRecognizer(mapDoubleTapReg)

}

override func viewWillAppear(_ animated: Bool) {
    super.viewWillAppear(animated)

    let backBtn = UIBarButtonItem(title: "Back", style: .plain, target: self, action: #selector(back) )

    navBar.topItem?.leftBarButtonItem = backBtn
}

var countTap:Int = 0
func mapTapHandle( tapReg: UITapGestureRecognizer ) {
    countTap += 1

    let location = tapReg.location(in: mapView)
    let coordinate = mapView.convert(location,toCoordinateFrom: mapView)

    print("Tap(\(countTap)) on mapView: \(coordinate.latitude),\(coordinate.longitude)")

    // add annotation

    let annotation = MKPointAnnotation()

    annotation.coordinate = coordinate
    annotation.title = "Tap(\(countTap))"
    annotation.subtitle = "\(coordinate.latitude),\(coordinate.longitude)"

    mapView.addAnnotation(annotation)

}

}