I'm making an app using apple's mapkit framework. What I want to do is to get longitude and latitude from a location that you press. I get the coordinates from the users current location using this code:
- (IBAction)longpressToGetLocation:(id)sender {
CLLocationCoordinate2D location = [[[self.mapView userLocation] location] coordinate];
NSLog(@"Location found from Map: %f %f",location.latitude,location.longitude);
}
How do I get that code to show the pressed location instead of userlocation?
First of all, use a UIGestureRecognizer
instead an IBAction
- (void)longpressToGetLocation:(UIGestureRecognizer *)gestureRecognizer
{
if (gestureRecognizer.state != UIGestureRecognizerStateBegan)
return;
CGPoint touchPoint = [gestureRecognizer locationInView:self.mapView];
CLLocationCoordinate2D location =
[self.mapView convertPoint:touchPoint toCoordinateFromView:self.mapView];
NSLog(@"Location found from Map: %f %f",location.latitude,location.longitude);
}
Swift 2:
@IBAction func revealRegionDetailsWithLongPressOnMap(sender: UILongPressGestureRecognizer) {
if sender.state != UIGestureRecognizerState.Began { return }
let touchLocation = sender.locationInView(protectedMapView)
let locationCoordinate = protectedMapView.convertPoint(touchLocation, toCoordinateFromView: protectedMapView)
print("Tapped at lat: \(locationCoordinate.latitude) long: \(locationCoordinate.longitude)")
}
Swift 3:
@IBAction func revealRegionDetailsWithLongPressOnMap(sender: UILongPressGestureRecognizer) {
if sender.state != UIGestureRecognizerState.began { return }
let touchLocation = sender.location(in: protectedMapView)
let locationCoordinate = protectedMapView.convert(touchLocation, toCoordinateFrom: protectedMapView)
print("Tapped at lat: \(locationCoordinate.latitude) long: \(locationCoordinate.longitude)")
}