在地图上处理水龙头

问题描述:

我有一个iOS应用程序,我需要干涉地图。 经过搜索,我得出结论,我必须使用MKMapView对象,并可能实现MKMapViewDelegate协议。在地图上处理水龙头

我现在想知道如何在用户点击地图时捕捉触摸点(意思是经度和方位角)。我想有一个更好的方法比摆弄一个自制的UITapGestureRecognizer

要清楚和简单,我有这样的代码开始:

import UIKit 
import CoreLocation 
import MapKit 

class ViewController: UIViewController, CLLocationManagerDelegate, MKMapViewDelegate { 
    let appDelegate = UIApplication.sharedApplication().delegate as! AppDelegate, 
    screenSize: CGRect = UIScreen.mainScreen().bounds, 
    locationManager = CLLocationManager() 
    ......... 

    override func viewDidLoad() { 
     super.viewDidLoad() 

     locationManager.delegate = self 
     locationManager.desiredAccuracy = kCLLocationAccuracyBest 
     ......... 

     let mapView = MKMapView(frame: CGRect(origin: CGPoint(x: 0.0, y: 20.0), 
      size: CGSize(width: screenSize.width, 
       height: screenSize.height-70.0))) 
     mapView.delegate = self 
     self.view.addSubview(mapView) 
    } 

    ......... 
} 

我的问题是:我有什么做处理的MapView对象用户的水龙头? 虽然我在写这篇文章之前一直在寻找这个问题,但我没有找到明确的解决方案。

+0

只有一种方法,它使用'TapGestureRecognizer'。 –

+0

您的意思是使用TapGestureRecognizer获取该点,然后使用地图的原点和缩放因子转换为地图坐标? – Michel

+0

是的,我同意'Nirav D'的评论,当我尝试处理相同的情况时,我搜索了很多,但最后我用'UITapGestureRecognizer'去了 –

通过查看documentation,没有任何处理触摸的方法。

我认为你必须使用UITapGestureRecognizer检测触摸。 touchesBegan不起作用,因为我认为地图视图拦截了它,就像表格视图一样。

在检测到触摸位置后,使用convert(_:toCoordinateFrom:)方法将地图视图的坐标空间中的CGPoint转换为地图上的CLLocationCoordinate2D

如果这听起来太麻烦了,您可以改用Google地图。 GMSMapView有一个可以实现的委托方法mapView(_:didTapAt:)方法。

请在viewDidLoad中加上UITapGestureRecognizer

let gestureRecognizer = UITapGestureRecognizer(target: self, action:#selector(ViewController.getCoordinatePressOnMap(sender:))) 
    gestureRecognizer.numberOfTapsRequired = 1 
    mapView.addGestureRecognizer(gestureRecognizer) 

执行getCoordinatePressOnMap方法。

@IBAction func getCoordinatePressOnMap(sender: UITapGestureRecognizer) { 
    let touchLocation = sender.location(in: mapView) 
    let locationCoordinate = mapView.convert(touchLocation, toCoordinateFrom: mapView) 
    print("Tapped at lat: \(locationCoordinate.latitude) long: \(locationCoordinate.longitude)") 
} 

注:

转换(_:toCoordinateFrom :):指定 视图的坐标系统中的点转换为地图坐标。

希望它适合你!