Search code examples
iosios4mkmapview

How can i get any information like lat,long when i touch on MKMapView in iPhone/iPad?


I have a mapView using xib file now when i touch in the mapview i want the latitude and longitude of that particular area so there any whey or any sample code which help me in this task.Thanks in Advance.


Solution

  • With iOS 3.2 or greater, it's probably better and simpler to use a UIGestureRecognizer with the map view instead of trying to subclass it and intercepting touches manually.

    First, add the gesture recognizer to the map view:

    UITapGestureRecognizer *tgr = [[UITapGestureRecognizer alloc] 
            initWithTarget:self action:@selector(tapGestureHandler:)];
    tgr.delegate = self;  //also add <UIGestureRecognizerDelegate> to @interface
    [mapView addGestureRecognizer:tgr];
    [tgr release];
    

    Next, implement shouldRecognizeSimultaneouslyWithGestureRecognizer and return YES so your tap gesture recognizer can work at the same time as the map's (otherwise taps on pins won't get handled automatically by the map):

    - (BOOL)gestureRecognizer:(UIGestureRecognizer *)gestureRecognizer 
        shouldRecognizeSimultaneouslyWithGestureRecognizer
            :(UIGestureRecognizer *)otherGestureRecognizer
    {
        return YES;
    }
    

    Finally, implement the gesture handler:

    - (void)tapGestureHandler:(UITapGestureRecognizer *)tgr
    {
        CGPoint touchPoint = [tgr locationInView:mapView];
    
        CLLocationCoordinate2D touchMapCoordinate 
            = [mapView convertPoint:touchPoint toCoordinateFromView:mapView];
    
        NSLog(@"tapGestureHandler: touchMapCoordinate = %f,%f", 
            touchMapCoordinate.latitude, touchMapCoordinate.longitude);
    }