0

I need to make a button that centers the map on user's location and another one that centers the map on specific coordinates (centroCU). When I run the app, the button shows, but the action doesn't work. What am I doing wrong? I got the code from Button to center view to user location using MapKit

 class ViewController: UIViewController, MKMapViewDelegate, CLLocationManagerDelegate {

    let map = MKMapView()
    let centroCU = CLLocationCoordinate2D(latitude: 25.72714,
                                            longitude: -100.31190)
...

 override func viewDidLoad() {
        super.viewDidLoad()

        view.addSubview(map)
        map.frame = view.bounds
        
        map.setRegion(MKCoordinateRegion(center: centroCU,
                                         span: MKCoordinateSpan(latitudeDelta: 0.013,
                                                                longitudeDelta: 0.013))
                      , animated: true)
        
        map.delegate = self
        addMapTrackingButton()
... 
    }

 func addMapTrackingButton(){
        let image = UIImage(named: "Recenter") as UIImage?
        let button   = UIButton(type: UIButton.ButtonType.custom) as UIButton
        button.frame = CGRect(origin: CGPoint(x: 315 , y: 50), size: CGSize(width: 45, height: 45))
        button.setImage(image, for: .normal)
        button.backgroundColor = .clear
        button.addTarget(self, action: #selector(ViewController.centerMapOnCentroCU), for:.touchUpInside)
        map.addSubview(button)
    }
    
    @objc func centerMapOnCentroCU() {
        map.setRegion(MKCoordinateRegion(center: CLLocationCoordinate2D(latitude: 25.72714,
                                            longitude: -100.31190),
                                         span: MKCoordinateSpan(latitudeDelta: 0.013,
                                                                longitudeDelta: 0.013))    }
...
}

1 Answers1

0

You already wrote a function centerMapOnCentroCU() that centers your map on the centroCU location. You need to call that function from your button's IBAction. If it isn't working, add a breakpoint or print statement to make sure the code is being executed.

And by the way, I would abstract your centerMapOnCentroCU() function into a function centerMapOnCoordinate(_ coordinate: CLLocationCoordinate2D) and have both of your button IBActions call that function, passing in the appropriate coordinate in each case.

Duncan C
  • 128,072
  • 22
  • 173
  • 272
  • Thanks for your answer, but actually I think it was an Xcode bug, I only moved my project's location, then moved it again to the original folder and the button started working perfectly:) Then I made the other button and both are working fine – Rubén Vásquez Apr 13 '22 at 21:54