Button to view the center in a custom location using MapKit

Is there a dedicated button in MapKit that centers the camera on the user's location? Or do I need to do this manually by creating a button and switching mapView.showsUserLocation = true ?

+5
source share
3 answers

This method works well (Swift), and you can customize the button:

 class YourViewController{ ... @IBOutlet weak var mapView:MKMapView ... override func viewDidLoad() { super.viewDidLoad() ... addMapTrackingButton() } func addMapTrackingButton(){ let image = UIImage(named: "trackme") as UIImage? let button = UIButton(type: UIButtonType.System) as UIButton button.frame = CGRectMake(5, 5, 35, 35) button.setImage(image, forState: .Normal) button.backgroundColor = .clearColor() button.addTarget(self, action: #selector(YourViewController.centerMapOnUserButtonClicked), forControlEvents:.TouchUpInside) self.mapView.addSubview(button) } func centerMapOnUserButtonClicked() { self.mapView.setUserTrackingMode( MKUserTrackingMode.Follow, animated: true) } ... } 

Swift 4:

 func addMapTrackingButton(){ let image = UIImage(named: "trackme") as UIImage? let button = UIButton(type: UIButtonType.custom) as UIButton button.frame = CGRect(origin: CGPoint(x:5, y: 25), size: CGSize(width: 35, height: 35)) button.setImage(image, for: .normal) button.backgroundColor = .clear button.addTarget(self, action: #selector(ViewController.centerMapOnUserButtonClicked), for:.touchUpInside) mapView.addSubview(button) } @objc func centerMapOnUserButtonClicked() { mapView.setUserTrackingMode(MKUserTrackingMode.follow, animated: true) } 
+5
source

I'll be late, ah, but I just found a function:

 CLLocationManager.requestLocation() 

So, once you have configured your locationManager manager correctly (using requestAlwaysAuthorization), you can call it wherever you want to center the map in your own location :)

+3
source

You need to take the coordinate of the user's location and set the area.

 - (IBAction)centerMapOnUserButtonClicked:(id)sender { MKCoordinateSpan span = MKCoordinateSpanMake(0.0001f, 0.0001f); CLLocationCoordinate2D coordinate = self.mapView.userLocation.coordinate; MKCoordinateRegion region = {coordinate, span}; MKCoordinateRegion regionThatFits = [self.mapView regionThatFits:region]; NSLog(@"Fit Region %f %f", regionThatFits.center.latitude, regionThatFits.center.longitude); [self.mapView setRegion:regionThatFits animated:YES]; } 

Solution 2:

 MKUserTrackingBarButtonItem *trackButton = [[MKUserTrackingBarButtonItem alloc] initWithMapView:mapView]; [trackButton setTarget:self]; [trackButton setAction:@selector(track:)]; [toolbar setItems:[NSArray arrayWithObjects:trackButton, nil] animated:YES]; 

Swift 4:

 let trackButton = MKUserTrackingBarButtonItem.init(mapView: mapView) trackButton.target = self trackButton.action = #selector(ViewController.track) toolbar.items?.append(trackButton) 
+1
source

Source: https://habr.com/ru/post/1240622/


All Articles