Get selected pin coordinate using MapKit framework (Objective-C)

676 Views Asked by At

I have a map region with about ten annotated MapPin objects (coordinates retrieved from a plist). In the code below 'locations' is a NSMutable array object containing the pin annotation latitude and longitude.

for (int i = 0; i<[locations count]; i++) {
        MKCoordinateSpan span = MKCoordinateSpanMake(0, 0);
        CLLocationCoordinate2D center = CLLocationCoordinate2DMake(0, 0);
        pinRegion = MKCoordinateRegionMake(center, span);
        MapPin *pin = [[MapPin alloc] init];

        pinRegion.center.longitude = [locations[i][0] doubleValue];
        pinRegion.center.latitude  = [locations[i][1] doubleValue];
        pin.title = names[i];
        pin.coordinate = pinRegion.center;

        [self.mapView addAnnotation:pin];

}

By selecting any pin I want to return its coordinate. I can inspect any pin object address like this:

NSLog(@"%@", self.mapView.selectedAnnotations);

... shows a unique address for a selected pin such as "<MapPin: 0x16d2f610>"

But I don't know how to access the objects coordinate properties such as longitude and latitude.

Please can you help?

Thank you!

1

There are 1 best solutions below

0
On

Make sure your map view has its delegate assigned (in this example we will use your view controller)

    mapView.delegate = self

Next handle the callback delegate for annotation taps like this:

Swift

func mapView(mapView: MKMapView, didSelectAnnotationView view: MKAnnotationView)
    {
        if let annotationCoordinate = view.annotation?.coordinate
        {
            print("User tapped on annotation with title: \(annotationCoordinate")
        }
    }

Objective - C

- (void)mapView:(MKMapView *)mapView didSelectAnnotationView:(MKAnnotationView *)view{

      NSLog(view.annotation.coordinate);
}

Let me know if you have any questions