请帮助初学iOS开发人员! :)所以,我有一个定时器,它可以定期从xml表中获取总线的经纬度,从而提供总线的实时位置。我能够设置解析器,为公交车运动设置动画并为公交车设置自定义(箭头)图像。自定义注释图像仅在程序开始时旋转(Swift-iOS)
但是,问题是,我无法在每次获得经纬度的新值时旋转总线注释。 busAnnotation
仅在程序启动时才旋转,但不是每次总线方向都会更新。
以下是我的xml parser
函数,该函数每当位置发生变化时都会计算出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;
}
你们认为我在这里错过了什么吗?每次更新位置时,我将如何旋转公交注释?提前致谢。
这工作完美!你救了我的命!非常感谢! :D – Mashfique
太棒了!如果我可以打扰你接受答案...... –