9

I can't figure out how to get the map to zoom in on the user location from viewDidLoad. I tried setting a region, and that didn't work. This is the code I have, any tips?

@IBOutlet weak var mapView: MKMapView! var MapViewLocationManager:CLLocationManager! = CLLocationManager() var currentLocation: PFGeoPoint! = PFGeoPoint()

override func viewDidLoad() {
    super.viewDidLoad()
    self.mapView.showsUserLocation = true
    mapView.delegate = self
   MapViewLocationManager.delegate = self
    mapView.setUserTrackingMode(MKUserTrackingMode.Follow, animated: true)
}

I have looked up the answers for this question but haven't found the answer in Swift or that actually works. Thanks!!

Caitlin
  • 93
  • 1
  • 1
  • 4

4 Answers4

18

I would try something like this:

    let latitude:CLLocationDegrees = //insert latitutde

    let longitude:CLLocationDegrees = //insert longitude

    let latDelta:CLLocationDegrees = 0.05

    let lonDelta:CLLocationDegrees = 0.05

    let span = MKCoordinateSpanMake(latDelta, lonDelta)

    let location = CLLocationCoordinate2DMake(latitude, longitude)

    let region = MKCoordinateRegionMake(location, span)

    mapView.setRegion(region, animated: false)

I saw you said you tried setting a region. Maybe try doing it this way.

Zee
  • 1,865
  • 21
  • 42
rb612
  • 5,280
  • 3
  • 30
  • 68
  • Thank you so much! I guess that is where I am stuck, how would I define the latitude and longitude of the user location? – Caitlin Jun 25 '15 at 03:36
  • @Caitlin you're welcome! I'm on mobile so I can't explain, but check this out: http://youtu.be/pSjbMwR2A2U and this: http://stackoverflow.com/a/25698536 if the video doesn't help. – rb612 Jun 25 '15 at 03:39
9

On most apps, a 'current location' button is implemented. A simple way to do it is like this:

@IBAction func myLocationButtonTapped(_ sender: Any) {

    mapView.showsUserLocation = true
    mapView.setUserTrackingMode(.follow, animated: true)

}

Once the user pans or zooms the map, the tracking will stop. So it's good enough for me.

AmitP
  • 5,353
  • 4
  • 35
  • 27
8

You have to try this. It will zooming map.

let span = MKCoordinateSpanMake(0.050, 0.050)
let region = MKCoordinateRegion(center: CLLocationCoordinate2D(latitude: 23.0225, longitude: 72.5714), span: span)
mapView.setRegion(region, animated: true)`
Sahil Kapoor
  • 11,183
  • 13
  • 64
  • 87
Jatin Patel
  • 396
  • 3
  • 14
  • and if you want to zoom more you just use smaller numbers in spam: `let spam = MKCoordinateSpanMake(0.001, 0.001)` – Pavlos Mar 26 '17 at 21:59
0
@IBOutlet weak var conscienceMap: MKMapView!

override func viewDidLoad() {
    super.viewDidLoad()
    conscienceMap.showsUserLocation = true
    conscienceMap.setUserTrackingMode(MKUserTrackingMode.follow, animated: true)
}
Wiza
  • 1
  • 1
  • 1
    Please provide an explanation of your code. Answers with only code aren't as good at helping others learn. – AlexH Nov 23 '20 at 23:27