Search code examples
iosxcodemkmapviewmkannotationmkannotationview

Show Annotation Pin on mapView when button is pressed


trying to figure out if it is possible when a button is pressed to go to a certain longitude and latitude in mapView and drop a button. I copied my code for a "newAnnotation" pin which previously worked, but realize now it might not be working inside of the code of my button. Here is my button code:

-(IBAction)buttonPressed 
{
CLLocationCoordinate2D location;
MKCoordinateSpan span;
location.latitude = (double) 44.4758;
    location.longitude = (double) -73.2125;
span.latitudeDelta=0.2;
span.longitudeDelta=0.2;


    MapViewAnnotation *newAnnotation = [[MapViewAnnotation alloc] initWithTitle:@"BCA" 
    andCoordinate:location];
[self.mapView addAnnotation:newAnnotation];
[newAnnotation release];


themapView = [[MapView alloc] initWithNibName:@"MapView" bundle:nil];
[self.view addSubview:themapView.view]; 
}

I know that the button WORKS and that it actually goes to the mapView and is processing the coordinates, but that it just isn't dropping the pin with the title. Currently there are no errors as my code stands. If you need to see other code, let me know. Thanks a million.


Solution

  • I think your problem is that you are adding an annotation to a map view that is not visible yet. You have to first add the map view view as a subview then add the annotation. Here is what the code would look like:

    -(IBAction)buttonPressed 
    {
    CLLocationCoordinate2D location;
    MKCoordinateSpan span;
    location.latitude = (double) 44.4758;
        location.longitude = (double) -73.2125;
    span.latitudeDelta=0.2;
    span.longitudeDelta=0.2;
    
    MapViewAnnotation *newAnnotation = [[MapViewAnnotation alloc] initWithTitle:@"BCA" 
    andCoordinate:location];
    [self.mapView addAnnotation:newAnnotation];
    [newAnnotation release];
    
    
    themapView = [[MapView alloc] initWithNibName:@"MapView" bundle:nil];
    [self.view addSubview:themapView.view]; 
    
    }
    

    UPDATE:

    Can we see the code for MapViewAnnotation. It should be an NSObject class which adopts MKAnnotation like this <MKAnnotation> and you should declare and synthesize three properties: title, subtitle if you like, and of course coordinate

    Another problem may be that you are adding MapView's view as a subview. It might be better to put this code in MapView and present MapView as a view controller

    I also do not understand why you are adding an annotation to self.mapView and then adding a subview over it.....