Tobbbe Tobbbe - 9 months ago 79
iOS Question

get tapped coordinates with iphone mapkit

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)

    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);



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