首页 > 解决方案 > 在地图中包裹纬度和经度时崩溃

问题描述

我获取当前用户地图位置并将其显示在以他的位置为地图中心的地图上。上线就崩溃了

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)

标签: mapkitlatitude-longitude

解决方案


试试下面的代码

    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)
    }

推荐阅读