Anonymous Dev Anonymous Dev - 8 months ago 49
Swift Question

Pressing Button Centers MKMapView onto User Location, Swift

My app includes MKMapView That Shows the user location.
i would like to crete a button that once pressed it should center the map view onto the user current location...Just like Apple Button does...Can anyone guide me on how to give the button this function?


On action of your button, call to update user's location and then on delegate:

-(void)mapView:(MKMapView *)mapView didUpdateUserLocation:(MKUserLocation *)userLocation 
MKCoordinateRegion mapRegion; = mapView.userLocation.coordinate;
mapRegion.span.latitudeDelta = 0.2;
mapRegion.span.longitudeDelta = 0.2;

[mapView setRegion:mapRegion animated: YES];

Updated for Swift:

 func locationManager(manager: CLLocationManager, didUpdateLocations locations: [CLLocation]) {
    var span = MKCoordinateSpanMake(0.2, 0.2)
    var region = MKCoordinateRegion(center: locations[0].coordinate, span: span)

    mapView.setRegion(region, animated: true)