如何在 Swift 中使用 magneticHeading



我正在尝试制作一个简单的脚导航器,使用箭头图像,旋转以指示要遵循的方向,并不断刷新。

使用magneticHeading我发现错误unexpectedly found nil while unwrapping an Optional value,也许我忘记了什么。

如何正确使用磁头?

var northLatitude :CLLocationDegrees 
var latitude :CLLocationDegrees = 46.0
var longitude :CLLocationDegrees = 7.0

func locationManager(manager: CLLocationManager!, didUpdateLocations locations: [AnyObject]!) {
    longitude = manager.location.coordinate.longitude
    latitude = manager.location.coordinate.latitude
    var buildingLocation:CLLocationCoordinate2D = CLLocationCoordinate2DMake(latitude, longitude)
    var regionOfInterest:MKCoordinateRegion = MKCoordinateRegionMake(buildingLocation, span)
    self.mapView.setRegion(regionOfInterest, animated: true)
    self.mapView.addAnnotation(buildingAnnotation)
    northLatitude = manager.heading.magneticHeading  //ERROR
}

您可以计算箭头应指向的角度,然后使用图像视图的 transform 属性更改方向。伪代码将是这样的。

func onPositionChange()
{
    UIView.animateWithDuration(1.0, animations:
        {
            var angle_in_degrees:CGFloat = 10 // Calculated Angle.
            var angle_in_radians = (angle_in_degrees * 3.1415) / 180.0
            self.imgView.transform = CGAffineTransformMakeRotation(angle_in_radians)
    })
}

最新更新