我有一个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,但我没有找到明确的解决方案。
答案 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 :):转换指定的点 视图的坐标系到地图坐标。
希望它适合你!!!