处理地图上的水龙头

时间:2016-12-02 06:46:51

标签: ios swift mkmapview mkmapviewdelegate

我有一个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对象上的用户点击? 虽然在写这篇文章之前我找到了anwer,但我没有找到明确的解决方案。

2 个答案:

答案 0 :(得分:0)

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

我认为您必须使用UITapGestureRecognizer检测触控。 touchesBegan无法正常工作,因为我认为地图视图会截取该视图,就像表视图一样。

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

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

答案 1 :(得分:0)

请在UITapGestureRecognizer中添加viewDidLoad

    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)")
}

注意:

  

convert(_:toCoordinateFrom :):转换指定的点   视图的坐标系到地图坐标。

希望它适合你!!!

相关问题