在地图中包装经纬度时发生崩溃

时间:2018-08-30 11:32:59

标签: mapkit latitude-longitude

我获得了当前用户地图的位置,并将其显示在以他的位置为地图中心的地图上。 它在行上崩溃

let currentLatitude = (locationManager.location?.coordinate.latitude)!
let currentLongitude = (locationManager.location?.coordinate.longitude)!

,出现错误“无法从第4角插入合法归属”

我认为这与纬度和经度的强制换行有关。我应如何解决此错误?

这是我的代码:

// Location Manager settings
locationManager.delegate = self
locationManager.desiredAccuracy = kCLLocationAccuracyBest
locationManager.requestWhenInUseAuthorization()
locationManager.startUpdatingLocation()

let currentLatitude = (locationManager.location?.coordinate.latitude)!
let currentLongitude = (locationManager.location?.coordinate.longitude)!

//Map settings
mapMyLocation.showsUserLocation = true
mapMyLocation.delegate = self
let locationcoordinates = CLLocationCoordinate2D(latitude: currentLatitude, longitude: currentLongitude)
let zoomSpan = MKCoordinateSpan(latitudeDelta: 0.5, longitudeDelta: 0.5)
let region = MKCoordinateRegion(center: locationcoordinates, span: zoomSpan)
mapMyLocation.setRegion(region, animated: true)

1 个答案:

答案 0 :(得分:0)

尝试以下代码

    if let currentLatitude = locationManager.location?.coordinate.latitude,
        let currentLongitude = locationManager.location?.coordinate.longitude {

        //Map settings
        mapMyLocation.showsUserLocation = true
        mapMyLocation.delegate = self
        let locationcoordinates = CLLocationCoordinate2D(latitude: currentLatitude, longitude: currentLongitude)
        let zoomSpan = MKCoordinateSpan(latitudeDelta: 0.5, longitudeDelta: 0.5)
        let region = MKCoordinateRegion(center: locationcoordinates, span: zoomSpan)
        mapMyLocation.setRegion(region, animated: true)
    }