请在这里帮助新手 iOS 开发者! :) 所以,我有一个计时器,它定期从提供公交车实时位置的 xml 表中获取公交车的纬度和经度。我能够设置解析器、为总线运动设置动画并为总线设置自定义(箭头)图像。
然而,问题是,每次获得纬度和经度的新值时,我无法旋转总线注释。这busAnnotation
仅在程序启动时旋转,而不是每次更新总线方向时旋转。
下面是我的xmlparser
函数,它计算busDirection
每次位置改变时。的价值busDirection
随着位置变化而正确变化,但随着计时器的继续,由于某种原因它不适用于旋转。注释的移动也具有良好的动画效果,只是在程序启动时不会旋转。
// Some constants
var oldLatitude: Double? = 44.97234
var oldLongitude: Double? = -93.2446329
var busDirection: CLLocationDirection()
func parser(parser: NSXMLParser!, didStartElement elementName: String!, namespaceURI: String!, qualifiedName qName: String!, attributes attributeDict: NSDictionary!) {
if (elementName == "vehicle") {
var latitude = attributeDict["lat"]?.doubleValue // Get latitude of bus from xml
var longitude = attributeDict["lon"]?.doubleValue // Get longitude of bus from xml
if (oldLatitude == latitude && oldLongitude == longitude) {
return
}
else { // Update bus location
busDirection = directionBetweenPoints(MKMapPointForCoordinate(CLLocationCoordinate2DMake(oldLatitude!, oldLongitude!)), destinationPoint: MKMapPointForCoordinate(CLLocationCoordinate2DMake(latitude!, longitude!))) // Get direction of bus:
UIView.animateWithDuration(0.5) {
self.busAnnotation.coordinate = CLLocationCoordinate2DMake(latitude!, longitude!)
self.mapView(self.map, viewForAnnotation: self.busAnnotation).annotation = self.busAnnotation
self.map.addAnnotation(self.busAnnotation)
}
oldLatitude = latitude
oldLongitude = longitude
}
}
}
这是我实现的“viewForAnnotation”,以便更改注释的图像并旋转它
func mapView(mapView: MKMapView!, viewForAnnotation annotation: MKAnnotation!) -> MKAnnotationView! {
let reuseId = "pin"
var pinView = mapView.dequeueReusableAnnotationViewWithIdentifier(reuseId) as? MKPinAnnotationView
if pinView == nil {
pinView = MKPinAnnotationView(annotation: annotation, reuseIdentifier: reuseId)
pinView!.image = imageWithImage(UIImage(named:"arrow.png")!, scaledToSize: CGSize(width: 25.0, height: 25.0)) // Set custom image for annotation and resize it
}
else {
pinView!.annotation = annotation
}
// Rotate the annotation.
pinView?.transform = CGAffineTransformRotate(self.map.transform, CGFloat(degreesToRadians(self.busDirection)))
return pinView
}
这些是我在上述方法中使用的一些辅助函数:
// For rotating bus annotations:
func degreesToRadians(degrees: Double) -> Double { return degrees * M_PI / 180.0 }
func radiansToDegrees(radians: Double) -> Double { return radians * 180.0 / M_PI }
func directionBetweenPoints(sourcePoint: MKMapPoint, destinationPoint : MKMapPoint) -> CLLocationDirection {
let x : Double = destinationPoint.x - sourcePoint.x;
let y : Double = destinationPoint.y - sourcePoint.y;
return fmod(radiansToDegrees(atan2(y, x)), 360.0) + 90.0;
}
你们认为我在这里遗漏了什么吗?每次更新位置时如何旋转总线注释?提前致谢。