2

My code:

Please anyone ! How to make this button work !?!??!

What do i put in the @IBAction brackets to have the function i want ?

    import UIKit
    import MapKit
    import CoreLocation

class MapViewController: UIViewController,MKMapViewDelegate, CLLocationManagerDelegate{



        @IBOutlet weak var mapView: MKMapView!



        let locationManager = CLLocationManager()

        override func viewDidLoad() {
            super.viewDidLoad()

            //==========RegionLocation : =========

            // Init the zoom level
            let coordinate:CLLocationCoordinate2D = CLLocationCoordinate2D(latitude: 31.30, longitude: 34.45)
            let span = MKCoordinateSpanMake(125, 125)
            let region = MKCoordinateRegionMake(coordinate, span)
            self.mapView.setRegion(region, animated: true)


            //====================================\\
        override func didReceiveMemoryWarning() {
            super.didReceiveMemoryWarning()
        //Dispose of resources that can be re created.

            }

        //Mark : Location

        func locationManager(manager: CLLocationManager, didUpdateLocations locations: [CLLocation])



        {
            let location = locations.last

            let center = CLLocationCoordinate2D(latitude: location!.coordinate.latitude, longitude: location!.coordinate.longitude)

            let region = MKCoordinateRegion(center: center, span: MKCoordinateSpan(latitudeDelta: 0.06, longitudeDelta: 0.06))

            self.mapView.setRegion(region, animated: true)

            self.locationManager.stopUpdatingLocation()
        }

        func locationManager(manager: CLLocationManager, didFailWithError error: NSError)
        {
            print("Errors: " + error.localizedDescription)
        }

        func mapView(mapView: MKMapView, viewForAnnotation annotation: MKAnnotation) -> MKAnnotationView? {
            if annotation is MKUserLocation {
                return nil
            }
            let reuseID = "pin"
            var pinView = mapView.dequeueReusableAnnotationViewWithIdentifier(reuseID) as? MKPinAnnotationView
            if(pinView == nil) {
                pinView = MKPinAnnotationView(annotation: annotation, reuseIdentifier: reuseID)
                pinView!.canShowCallout = true
                pinView!.animatesDrop = true
                pinView!.rightCalloutAccessoryView = UIButton(type: UIButtonType.DetailDisclosure) as UIButton
                let smallSquare = CGSize(width: 30, height: 30)
                let button = UIButton(frame: CGRect(origin: CGPointZero, size: smallSquare))
                button.setBackgroundImage(UIImage(named: "Car"), forState: .Normal)
                pinView?.leftCalloutAccessoryView = button
            }
            else
            {
                pinView!.annotation = annotation
            }


        return pinView

    }

but when i put in the button action segment nothing happens when i press on it ?

Anyone can Guide me on How do i center the mapView onto the user location Blue dot ?

Newbie Questions
  • 463
  • 1
  • 11
  • 31

3 Answers3

4

Try this

@IBAction func centerLocationButton(sender: UIButton) {
    mapView.setCenterCoordinate(mapView.userLocation.coordinate, animated: true)
}
1

In order to use MKMapView in correct way just follow the following below code.

// `viewDidLoad` method
@IBOutlet weak var map: MKMapView!
var locationManager: CLLocationManager!

override func viewDidLoad() {
        super.viewDidLoad()

        // code for enable location seivices
        if (CLLocationManager.locationServicesEnabled())
        {
            locationManager = CLLocationManager()
            locationManager.delegate = self
            locationManager.desiredAccuracy = kCLLocationAccuracyBest
            locationManager.requestAlwaysAuthorization()
            locationManager.startUpdatingLocation()
        }
    }

override CLLocationManager.didUpdateLocations see below (part of CLLocationManagerDelegate) to get notified when the location manager retrieves the current location.

func locationManager(manager: CLLocationManager!, didUpdateLocations locations: [AnyObject]!) {
    let location = locations.last as CLLocation

    let center = CLLocationCoordinate2D(latitude: location.coordinate.latitude, longitude: location.coordinate.longitude)        
    let region = MKCoordinateRegion(center: center, span: MKCoordinateSpan(latitudeDelta: 0.01, longitudeDelta: 0.01))

    self.map.setRegion(region, animated: true)
}

have a note: If your target is iOS 8, you must include the NSLocationAlwaysUsageDescription key in your Info.plist to get the location services to work.

if you want to set region in a custom way using button action just save lat and long and pass like:

@IBAction func setMap(sender: UIButton) {
    let center = CLLocationCoordinate2D(latitude: lat, longitude: long)        
    let region = MKCoordinateRegion(center: center, span: MKCoordinateSpan(latitudeDelta: 0.01, longitudeDelta: 0.01))
    self.map.setRegion(region, animated: true)
}

here is Google map guidelines. and useful tutorial

vaibhav
  • 4,038
  • 1
  • 21
  • 51
0

I can see what you need is to have a button to center the mapView to your current location. It is exactly same as vaibhab's answer with little modifications. Just create to button and link the action to the viewcontroller class then copy the same code in the IBAction of the button.

@IBAction func updateCurrentLocation(_ sender: AnyObject) {

    if CLLocationManager.locationServicesEnabled() {

        locationManager.delegate = self
        locationManager.desiredAccuracy = kCLLocationAccuracyBest
        locationManager.requestWhenInUseAuthorization()
        locationManager.startUpdatingLocation()
    } else {

        // Alert to enable location services on iphone first
    }
}

Plus you can just add a small line of code to show the blue indicator of the location of the user. In the func locationManager.

func locationManager(_ manager: CLLocationManager, didUpdateLocations locations: [AnyObject]) {

    self.mapView.showsUserLocation = true

}

Make sure when you are using the simulator just add a custom location from the simulators menu. Debug ---> location ----> Custom If using a real mobile just make sure that the location services is on in the Settings---> General----> Privacy

Kegham K.
  • 1,589
  • 22
  • 40