iosmkmapviewmkannotationmkuserlocation

Only add pin when button is clicked


I have this code that I need altered slightly. The code I have below creates a pin on my current location (perfectly as I might add).

The only problem is that I need the code only to be run when I click a button, not every time I move.

Here is the code of the current location and the pin.

- (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, 700, 700);
    [self.mapView setRegion:[self.mapView regionThatFits:region] animated:YES];

    // add the annotation
    MKPointAnnotation *point = [[MKPointAnnotation alloc] init];
    point.coordinate = userLocation.coordinate;
    point.title = @"Your Car";
    //point.subtitle = @"";
    [self.mapView addAnnotation:point];
}

I need this to run when I click a button such as:

-(IBAction)addPin
{
}

Solution

  • In the viewDidLoad: method,

    Create a button like this:

    UIButton *button = [UIButton buttonWithType:UIButtonTypeRoundedRect];
    [button addTarget:self 
           action:@selector(showPinOnClick)
     forControlEvents:UIControlEventTouchUpInside];
    [button setTitle:@"Show View" forState:UIControlStateNormal];
    button.frame = CGRectMake(100.0, 200.0, 150.0, 60.0);
    [self.view addSubview:button];
    

    // create the method defined as selector method for the UIButton in your viewcontroller

    -(void) showPinOnClick{
    //paste your code here to show the pin
    
    CLLocationCoordinate2D location = self.mapview.userLocation.coordinate;
    MKCoordinateRegion region;
    MKCoordinateSpan span;
    
    location.latitude  = -32.008081;
    location.longitude = 115.757671;
    
    span.latitudeDelta = 0.03;
    span.longitudeDelta = 0.03;
    
    region.span = span;
    region.center = location;
    
    
    [_mapview setRegion:region animated:YES];
    [_mapview regionThatFits:region];
    
    //Create your annotation
    MKPointAnnotation *point = [[MKPointAnnotation alloc] init];
    // Set your annotation to point at your coordinate
    point.coordinate = location;
    
    point.title = @"Your Car";
    
    
    //Drop pin on map
    [_mapview addAnnotation:point];
    [_mapview selectAnnotation:point animated:NO];
    
    }