MKMapView center and zoom in

后端 未结 9 1703
一向
一向 2021-02-19 23:16

I am using MKMapView on a project and would like to center the map on a coordinate and zoom in. Just like Google maps has:

GMSCameraPosition.camera(withLatitude:         


        
9条回答
  •  臣服心动
    2021-02-19 23:32

    Swift 3.0

    In the MapKit Function didUpdateLocations:

    func locationManager(_ manager: CLLocationManager, didUpdateLocations locations: [CLLocation]) {
                guard let location = locations.last as CLLocation? else { return }
    
                let userCenter = CLLocationCoordinate2D(latitude: location.coordinate.latitude, longitude: location.coordinate.longitude)
                // Does not have to be userCenter, could replace latitude: and longitude: with any value you would like to center in on
    
                let region = MKCoordinateRegion(center: userCenter, span: MKCoordinateSpan(latitudeDelta: 180, longitudeDelta: 180))
    
                mkView.setRegion(region, animated: true)
    
        }
    

    Note: If you do not want to keep setting the center every time there is a location update, then do the following:

            let userCenter = CLLocationCoordinate2D(latitude: location.coordinate.latitude, longitude: location.coordinate.longitude)
            // Does not have to be userCenter, could replace latitude: and longitude: with any value you would like to center in on
    
            let region = MKCoordinateRegion(center: userCenter, span: MKCoordinateSpan(latitudeDelta: 180, longitudeDelta: 180))
    
            mkView.setRegion(region, animated: true)
    

提交回复
热议问题