Search code examples
ipadiosmapkitmkannotation

iOS MapKit: Selected MKAnnotation coordinates


Using the code at the following tutorial, http://www.zenbrains.com/blog/en/2010/05/detectar-cuando-se-selecciona-una-anotacion-mkannotation-en-mapa-mkmapview/, I was able to add an observer to each MKAnnotation and receive a notification of selected/deselected states.

I am attempting to add a UIView on top of the selection annotation to display relevant information about the location. This information cannot be conveyed in the 2 lines allowed (Title/Subtitle) for the pin's callout.

- (void)observeValueForKeyPath:(NSString *)keyPath
                      ofObject:(id)object
                        change:(NSDictionary *)change
                       context:(void *)context {

    Annotation *a = (Annotation *)object;
    // Alternatively attempted using:
    //Annotation *a = (Annotation *)[mapView.selectedAnnotations objectAtIndex:0];


    NSString *action = (NSString *)context;
    if ([action isEqualToString:ANNOTATION_SELECTED_DESELECTED]) {
        BOOL annotationSelected = [[change valueForKey:@"new"] boolValue];
        if (annotationSelected) {
            // Actions when annotation selected
            CGPoint origin = a.frame.origin;
            NSLog(@"origin (%f, %f) ", origin.x, origin.y);

            // Test
            UIView *v = [[UIView alloc] init];
            [v setBackgroundColor:[UIColor orangeColor]];
            [v setFrame:CGRectMake(origin.x, origin.y , 300, 300)];
            [self.view addSubview:v];
            [v release];
        }else {
            // Accions when annotation deselected
        }
    }
}

Results using Annotation *a = (Annotation *)object

origin (154373.000000, 197135.000000) 
origin (154394.000000, 197152.000000) 
origin (154445.000000, 197011.000000) 

Results using Annotation *a = (Annotation *)[mapView.selectedAnnotations objectAtIndex:0];

origin (0.000000, 0.000000) 
origin (0.000000, 0.000000) 
origin (0.000000, 0.000000) 

The numbers are large. They are not relative to the view (1024 x 768). I believe they are relative to the entire map. How would I be able to detect the exact coordinates relative to the entire view so that I can appropriately position my view?

Note:

Just discovered these two methods which can probably accomplish the same thing as the code above in a much simpler implementation.

Selecting Annotation Views

– mapView:didSelectAnnotationView:
– mapView:didDeselectAnnotationView:

http://developer.apple.com/library/ios/#documentation/MapKit/Reference/MKMapViewDelegate_Protocol/MKMapViewDelegate/MKMapViewDelegate.html


Solution

  • Instead of using .frame.origin, try getting the MKAnnotation's coordinate property. Using this coordinate, you can use MKMapView's convertCoordinate:toPointToView: to get the origin of the annotation.

    Hope this helps!