Search code examples
iosdictionarymkmapview

Drop Pin on current location


I am building an iOS app and need to be able to place a pin where the user currently is! For some reason I have been having an awful time getting it to work! I tried the following code but was faced with an error.

- (MKAnnotationView *) mapView:(MKMapView *)mapView viewForAnnotation:(id <MKAnnotation>) annotation{

    if (annotation == mapView.userLocation)
    {

        MKPinAnnotationView *annView=[[MKPinAnnotationView alloc] initWithAnnotation:annotation reuseIdentifier:nil];
        annView.pinColor = MKPinAnnotationColorRed;
        annView.animatesDrop=TRUE;
        annView.canShowCallout = YES;
        annView.calloutOffset = CGPointMake(-5, 5);
        return annView;
        [annView release];



    }
}

The error was: Control May Reach End of non-void function.

Thank you so much for the help! ' Appreciate it!


Solution

  • The following code works fine in the Xcode iPhone simulator:

    #import "ViewController.h"
    @import MapKit;
    
    @interface ViewController () <MKMapViewDelegate>
    
    @property (weak, nonatomic) IBOutlet MKMapView *mapView;
    
    @end
    
    @implementation ViewController
    
    - (void)viewDidLoad {
        [super viewDidLoad];
    
        [self.mapView setDelegate:self];
        [self.mapView setShowsUserLocation:YES];
    }
    
    - (void)mapView:(MKMapView *)mapView didUpdateUserLocation:(MKUserLocation *)userLocation {
    
        // zoom to region containing the user location
        MKCoordinateRegion region = MKCoordinateRegionMakeWithDistance(userLocation.coordinate, 800, 800);
        [self.mapView setRegion:[self.mapView regionThatFits:region] animated:YES];
    
        // add the annotation
        MKPointAnnotation *point = [[MKPointAnnotation alloc] init];
        point.coordinate = userLocation.coordinate;
        point.title = @"The Location";
        point.subtitle = @"Sub-title";
        [self.mapView addAnnotation:point];
    }
    
    @end