簡體   English   中英

MKMapView 不斷監控航向

[英]MKMapView constantly monitor heading

我在位於我的MKMapView頂部的圖層中渲染一些內容。 除了旋轉之外,整個事情都很好。 當用戶旋轉地圖時,我需要能夠旋轉我在自己的圖層中渲染的內容。

我發現的標准答案是使用:

NSLog(@"heading: %f", self.mapView.camera.heading");

這樣做的問題是,heading 變量的內容僅在捏/旋轉手勢結束時更新,而不是在手勢期間更新。 我需要更頻繁的更新。

mapView本身沒有標題屬性。

我想也許像這樣使用KVO

    // Somewhere in setup
    [self.mapView.camera addObserver:self forKeyPath:@"heading" options:NSKeyValueObservingOptionNew context:NULL];


    // KVO Callback
    -(void)observeValueForKeyPath:(NSString *)keyPath
                         ofObject:(id)object
                           change:(NSDictionary *)change
                          context:(void *)context{

        if([keyPath isEqualToString:@"heading"]){
            // New value
        }
    }

然而, KVO監聽器永遠不會觸發,這並不奇怪。

有沒有我忽略的方法?

檢查以下答案,您可以使用CADisplayLink調整:

MapView檢測滾動

似乎確實沒有辦法在旋轉地圖時跟蹤簡單讀取的當前航向。 由於我剛剛實現了隨地圖旋轉的羅盤視圖,因此我想與您分享我的知識。

我明確邀請您改進此答案。 由於我有最后期限,所以現在就很滿意(在此之前,僅在地圖停止旋轉的那一刻才設置了指南針),但仍有改進和微調的空間。

我在此處上傳了一個示例項目: MapRotation示例項目

好的,讓我們開始吧。 由於我假設您現在都使用情節提要,因此將一些手勢識別器拖到地圖上。 (那些不確定地知道如何將這些步驟轉換為書面形式的人。)

要檢測地圖旋轉,縮放和3D角度,我們需要旋轉,平移和捏合手勢識別器。 在MapView上拖動手勢識別器

禁用旋轉手勢識別器的“延遲觸摸結束” ... 禁用旋轉手勢識別器的“延遲觸摸結束”

...,並將“手勢”識別器的“觸摸”增加到2。 將“平移手勢識別器”的“ Touchs”增加到2

將這3個的委托設置到包含的視圖控制器。 Ctrl拖動到包含的視圖控制器... ...並設置代表。

將所有3個手勢識別器都將“引用出口集合”拖到MapView中,然后選擇“ gestureRecognizers”

在此處輸入圖片說明

現在,將Ctrl旋轉手勢識別器作為Outlet拖到實現中,如下所示:

 @IBOutlet var rotationGestureRecognizer: UIRotationGestureRecognizer! 

以及所有3個識別器為IBAction:

 @IBAction func handleRotation(sender: UIRotationGestureRecognizer) { ... } @IBAction func handleSwipe(sender: UIPanGestureRecognizer) { ... } @IBAction func pinchGestureRecognizer(sender: UIPinchGestureRecognizer) { ... } 

是的,我將平移手勢命名為“ handleSwype”。 解釋如下。 :)

下面列出了控制器的完整代碼,當然,該代碼也必須實現MKMapViewDelegate協議。 我試圖在評論中非常詳細。

// compassView is the container View,
// arrowImageView is the arrow which will be rotated
@IBOutlet weak var compassView: UIView!
var arrowImageView = UIImageView(image: UIImage(named: "Compass")!)

override func viewDidLoad() {
    super.viewDidLoad()
    compassView.addSubview(arrowImageView)
}

// ******************************************************************************************
//                                                                                          *
// Helper: Detect when the MapView changes                                                  *

private func mapViewRegionDidChangeFromUserInteraction() -> Bool {
    let view = mapView!.subviews[0]
    // Look through gesture recognizers to determine whether this region
    // change is from user interaction
    if let gestureRecognizers = view.gestureRecognizers {
        for recognizer in gestureRecognizers {
            if( recognizer.state == UIGestureRecognizerState.Began ||
                recognizer.state == UIGestureRecognizerState.Ended ) {
                return true
            }
        }
    }
    return false
}
//                                                                                          *
// ******************************************************************************************



// ******************************************************************************************
//                                                                                          *
// Helper: Needed to be allowed to recognize gestures simultaneously to the MapView ones.   *

func gestureRecognizer(_: UIGestureRecognizer,
    shouldRecognizeSimultaneouslyWithGestureRecognizer:UIGestureRecognizer) -> Bool {
        return true
}
//                                                                                          *
// ******************************************************************************************



// ******************************************************************************************
//                                                                                          *
// Helper: Use CADisplayLink to fire a selector at screen refreshes to sync with each       *
// frame of MapKit's animation

private var displayLink : CADisplayLink!

func setUpDisplayLink() {
    displayLink = CADisplayLink(target: self, selector: "refreshCompassHeading:")
    displayLink.addToRunLoop(NSRunLoop.currentRunLoop(), forMode: NSRunLoopCommonModes)
}
//                                                                                          *
// ******************************************************************************************





// ******************************************************************************************
//                                                                                          *
// Detect if the user starts to interact with the map...                                    *

private var mapChangedFromUserInteraction = false

func mapView(mapView: MKMapView, regionWillChangeAnimated animated: Bool) {

    mapChangedFromUserInteraction = mapViewRegionDidChangeFromUserInteraction()

    if (mapChangedFromUserInteraction) {

        // Map interaction. Set up a CADisplayLink.
        setUpDisplayLink()
    }
}
//                                                                                          *
// ******************************************************************************************
//                                                                                          *
// ... and when he stops.                                                                   *

func mapView(mapView: MKMapView, regionDidChangeAnimated animated: Bool) {

    if mapChangedFromUserInteraction {

        // Final transform.
        // If all calculations would be correct, then this shouldn't be needed do nothing.
        // However, if something went wrong, with this final transformation the compass
        // always points to the right direction after the interaction is finished.
        // Making it a 500 ms animation provides elasticity und prevents hard transitions.

        UIView.animateWithDuration(0.5, animations: {
            self.arrowImageView.transform =
                CGAffineTransformMakeRotation(CGFloat(M_PI * -mapView.camera.heading) / 180.0)
        })



        // You may want this here to work on a better rotate out equation. :)

        let stoptime = NSDate.timeIntervalSinceReferenceDate()
        print("Needed time to rotate out:", stoptime - startRotateOut, "with velocity",
            remainingVelocityAfterUserInteractionEnded, ".")
        print("Velocity decrease per sec:", (Double(remainingVelocityAfterUserInteractionEnded)
            / (stoptime - startRotateOut)))



        // Clean up for the next rotation.

        remainingVelocityAfterUserInteractionEnded = 0
        initialMapGestureModeIsRotation = nil
        if let _ = displayLink {
            displayLink.invalidate()
        }
    }
}
//                                                                                          *
// ******************************************************************************************





// ******************************************************************************************
//                                                                                          *
// This is our main function. The display link calls it once every display frame.           *

// The moment the user let go of the map.
var startRotateOut = NSTimeInterval(0)

// After that, if there is still momentum left, the velocity is > 0.
// The velocity of the rotation gesture in radians per second.
private var remainingVelocityAfterUserInteractionEnded = CGFloat(0)

// We need some values from the last frame
private var prevHeading = CLLocationDirection()
private var prevRotationInRadian = CGFloat(0)
private var prevTime = NSTimeInterval(0)

// The momentum gets slower ower time
private var currentlyRemainingVelocity = CGFloat(0)

func refreshCompassHeading(sender: AnyObject) {

    // If the gesture mode is not determinated or user is adjusting pitch
    // we do obviously nothing here. :)
    if initialMapGestureModeIsRotation == nil || !initialMapGestureModeIsRotation! {
        return
    }


    let rotationInRadian : CGFloat

    if remainingVelocityAfterUserInteractionEnded == 0 {

        // This is the normal case, when the map is beeing rotated.
        rotationInRadian = rotationGestureRecognizer.rotation

    } else {

        // velocity is > 0 or < 0.
        // This is the case when the user ended the gesture and there is
        // still some momentum left.

        let currentTime = NSDate.timeIntervalSinceReferenceDate()
        let deltaTime = currentTime - prevTime

        // Calculate new remaining velocity here.
        // This is only very empiric and leaves room for improvement.
        // For instance I noticed that in the middle of the translation
        // the needle rotates a bid faster than the map.
        let SLOW_DOWN_FACTOR : CGFloat = 1.87
        let elapsedTime = currentTime - startRotateOut

        // Mathematicians, the next line is for you to play.
        currentlyRemainingVelocity -=
            currentlyRemainingVelocity * CGFloat(elapsedTime)/SLOW_DOWN_FACTOR


        let rotationInRadianSinceLastFrame =
        currentlyRemainingVelocity * CGFloat(deltaTime)
        rotationInRadian = prevRotationInRadian + rotationInRadianSinceLastFrame

        // Remember for the next frame.
        prevRotationInRadian = rotationInRadian
        prevTime = currentTime
    }

    // Convert radian to degree and get our long-desired new heading.
    let rotationInDegrees = Double(rotationInRadian * (180 / CGFloat(M_PI)))
    let newHeading = -mapView!.camera.heading + rotationInDegrees

    // No real difference? No expensive transform then.
    let difference = abs(newHeading - prevHeading)
    if difference < 0.001 {
        return
    }

    // Finally rotate the compass.
    arrowImageView.transform =
        CGAffineTransformMakeRotation(CGFloat(M_PI * newHeading) / 180.0)

    // Remember for the next frame.
    prevHeading = newHeading
}
//                                                                                          *
// ******************************************************************************************



// As soon as this optional is set the initial mode is determined.
// If it's true than the map is in rotation mode,
// if false, the map is in 3D position adjust mode.

private var initialMapGestureModeIsRotation : Bool?



// ******************************************************************************************
//                                                                                          *
// UIRotationGestureRecognizer                                                              *

@IBAction func handleRotation(sender: UIRotationGestureRecognizer) {

    if (initialMapGestureModeIsRotation == nil) {
        initialMapGestureModeIsRotation = true
    } else if !initialMapGestureModeIsRotation! {
        // User is not in rotation mode.
        return
    }


    if sender.state == .Ended {
        if sender.velocity != 0 {

            // Velocity left after ending rotation gesture. Decelerate from remaining
            // momentum. This block is only called once.
            remainingVelocityAfterUserInteractionEnded = sender.velocity
            currentlyRemainingVelocity = remainingVelocityAfterUserInteractionEnded
            startRotateOut = NSDate.timeIntervalSinceReferenceDate()
            prevTime = startRotateOut
            prevRotationInRadian = rotationGestureRecognizer.rotation
        }
    }
}
//                                                                                          *
// ******************************************************************************************
//                                                                                          *
// Yes, there is also a SwypeGestureRecognizer, but the length for being recognized as      *
// is far too long. Recognizing a 2 finger swype up or down with a PanGestureRecognizer
// yields better results.

@IBAction func handleSwipe(sender: UIPanGestureRecognizer) {

    // After a certain altitude is reached, there is no pitch possible.
    // In this case the 3D perspective change does not work and the rotation is initialized.
    // Play with this one.
    let MAX_PITCH_ALTITUDE : Double = 100000

    // Play with this one for best results detecting a swype. The 3D perspective change is
    // recognized quite quickly, thats the reason a swype recognizer here is of no use.
    let SWYPE_SENSITIVITY : CGFloat = 0.5 // play with this one

    if let _ = initialMapGestureModeIsRotation {
        // Gesture mode is already determined.
        // Swypes don't care us anymore.
        return
    }

    if mapView?.camera.altitude > MAX_PITCH_ALTITUDE {
        // Altitude is too high to adjust pitch.
        return
    }


    let panned = sender.translationInView(mapView)

    if fabs(panned.y) > SWYPE_SENSITIVITY {
        // Initial swype up or down.
        // Map gesture is most likely a 3D perspective correction.
        initialMapGestureModeIsRotation = false
    }
}
//                                                                                          *
// ******************************************************************************************
//                                                                                          *

@IBAction func pinchGestureRecognizer(sender: UIPinchGestureRecognizer) {
    // pinch is zoom. this always enables rotation mode.
    if (initialMapGestureModeIsRotation == nil) {
        initialMapGestureModeIsRotation = true
        // Initial pinch detected. This is normally a zoom
        // which goes in hand with a rotation.
    }
}
//                                                                                          *
// ******************************************************************************************

而不是傳遞nil上下文,而是傳遞一個值與您的KVO觀察者進行比較,如下所示:

static void *CameraContext= &CameraContext;

    // Somewhere in setup
    [self.mapView.camera addObserver:self forKeyPath:@"heading" options:NSKeyValueObservingOptionInitial | NSKeyValueObservingOptionNew context:CameraContext];


// KVO Callback
-(void)observeValueForKeyPath:(NSString *)keyPath
                     ofObject:(id)object
                       change:(NSDictionary *)change
                      context:(void *)context{

 if (context == CameraContext) {
    if([keyPath isEqualToString:@"heading"]){
        // New value
    }
  }
}

我已經在OS X的MapKit程序中看到了類似的行為。我正在使用<MKMapViewDelegate>調用mapView:regionDidChangeAnimated:而不是heading更改的KVO通知,但是我仍然只看到在結尾處的調用旋轉。

我只是嘗試實現mapView:regionWillChangeAnimated: 實際上,這確實在輪換開始時被調用。 也許您可以在收到mapView:regionWillChangeAnimated:開始輪詢該區域,然后停止對mapView:regionDidChangeAnimated:輪詢,並且在此之間進行輪換過程中所需的任何重要更新。

在 iOS11 中,我們使用 mapviewdidchangevisibleregion,它在手動旋轉地圖時被多次調用,我們讀取 map.camera.heading 來更改注釋

見 mapviewdidchangevisibleregion

在 iOS11 之前,我們在地圖上使用 UIRotationGestureRecognizer 來捕捉它......

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM