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

问题描述 投票:0回答:1

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

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)
mapkit latitude-longitude
1个回答
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)
    }
© www.soinside.com 2019 - 2024. All rights reserved.