Current location button on ios MKMapView
Asked Answered
C

4

17

I am using MKMapView in my iOS Application. I have search bar in my view. If I search for location on map, I am putting annotation on that searched location. Now the issue is, I want to go back to my current location. I have seen Google Maps application, they have one button on Map which will send the user to current location.

How to show that button?. And how to get click event of that button?.

Connie answered 14/11, 2014 at 11:28 Comment(1)
#6170419Winer
L
13
- (void)viewDidLoad
{
    [super viewDidLoad];    
    MKUserTrackingBarButtonItem *buttonItem = [[MKUserTrackingBarButtonItem alloc] initWithMapView:self.map];
    self.navigationItem.rightBarButtonItem = buttonItem;
}
Levitan answered 24/6, 2016 at 8:52 Comment(0)
H
8

SOLUTION 1:

Drag a UIButton to your UIViewController in the storyboard and connect it to an IBAction in the ViewController.m.

-(IBAction)zoomToUserLocation:(id)sender{
    MKCoordinateRegion mapRegion;   
    mapRegion.center = mapView.userLocation.coordinate;
    mapRegion.span.latitudeDelta = 0.2;
    mapRegion.span.longitudeDelta = 0.2;

    [mapView setRegion:mapRegion animated: YES];
}

SOLUTION 2:

Or you can create your button programmatically like this:

UIButton *button = [UIButton buttonWithType:UIButtonTypeCustom];
[button addTarget:self 
       action:@selector(zoomToUserLocation)
 forControlEvents:UIControlEventTouchUpInside];

[button setTitle:@"My Location" forState:UIControlStateNormal];
button.frame = CGRectMake(80.0, 210.0, 160.0, 40.0);
[view addSubview:button];

with the following method:

-(void)zoomToUserLocation{
    MKCoordinateRegion mapRegion;   
    mapRegion.center = mapView.userLocation.coordinate;
    mapRegion.span.latitudeDelta = 0.2;
    mapRegion.span.longitudeDelta = 0.2;

    [mapView setRegion:mapRegion animated: YES];
}
Handfast answered 15/1, 2016 at 14:40 Comment(2)
This sends map to user location, but how to add the button?Unreserved
@selector(zoomToUserLocation) remove ":" cause you don't need to send button to method as paramSpringer
D
7

Swift 3+

let buttonItem = MKUserTrackingBarButtonItem(mapView: mapView)
self.navigationItem.rightBarButtonItem = buttonItem
Direction answered 8/10, 2017 at 9:4 Comment(0)
B
0

You need to create a MKUserTrackingBarButtonItem and pass it the MKMapview in the constructor, then add that button item to the navigation menu (or where ever it is your button should be).

(void) viewDidLoad
{
    [super viewDidLoad];    
    MKUserTrackingBarButtonItem *buttonItem = [[MKUserTrackingBarButtonItem alloc] initWithMapView:self.map];
    self.navigationItem.rightBarButtonItem = buttonItem;
}
Belton answered 24/6, 2016 at 8:59 Comment(0)

© 2022 - 2024 — McMap. All rights reserved.