Reputation: 11749
I have an iOS
app where I need to interfere with a map.
After searching a bit I came to the conclusion that I have to use an MKMapView
object and probably implement the MKMapViewDelegate
protocol.
I am now wondering how I can capture the touch point (meaning longitude and lattitude) when the user taps on the map. I suppose there is a much better way than fiddling around with a home made UITapGestureRecognizer
.
To make it clear and simple, I have this kind of code to start with:
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)
}
.........
}
My question is: what do I have to do to handle the tap of the user on the mapView object? Though I looked for the anwer before writing this post, I came with no clear solution.
Upvotes: 1
Views: 817
Reputation: 7019
Please add the UITapGestureRecognizer
in viewDidLoad
.
let gestureRecognizer = UITapGestureRecognizer(target: self, action:#selector(ViewController.getCoordinatePressOnMap(sender:)))
gestureRecognizer.numberOfTapsRequired = 1
mapView.addGestureRecognizer(gestureRecognizer)
Implementation of getCoordinatePressOnMap
method.
@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)")
}
Note :
convert(_:toCoordinateFrom:) : Converts a point in the specified view’s coordinate system to a map coordinate.
Hope it works for you!!!
Upvotes: 3
Reputation: 272665
By looking at the documentation, there isn't any method that handles touches.
I think you have to detect touch using UITapGestureRecognizer
. touchesBegan
doesn't work because I think the map view intercepts that, just like a table view.
After you detected the touch location, use the convert(_:toCoordinateFrom:)
method to convert the CGPoint
in the map view's coordinate space to a CLLocationCoordinate2D
on the map.
If this all sounds too troublesome, you can use Google Maps instead. GMSMapView
has a delegate method mapView(_:didTapAt:)
method that you can implement.
Upvotes: 0