3
3

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?

More than 3 years have passed since last update.

[SwiftUI]MapKitのAnnotationを動かす

Posted at

SwiftUIでMapKitのアノテーションを自動で動かす画面を作りました。

完成図

ezgif.com-video-to-gif.gif

コード

import SwiftUI
import MapKit

struct MapAnimationView: View {
    @State dynamic var longitude:Double = 139.745451
    @State dynamic var latitude:Double = 35.658577
    var targetLongitude:Double = 143.1212
    var body: some View {
        VStack{
            Button(action:{
                self.move()
            }){
                Text("Move")
            }
            AnimationMapView(lon:self.$longitude, lat:self.$latitude)
        }
    }
    
    func move(){
        self.longitude = self.targetLongitude
    }
}


struct AnimationMapView: UIViewRepresentable {
    @Binding dynamic var lon:Double
    @Binding dynamic var lat:Double
    
    func makeUIView(context: UIViewRepresentableContext<AnimationMapView>) -> MKMapView {
        let view = MKMapView(frame: .zero)
        
        // 初期位置にピンを追加
        let annotation = MKPointAnnotation()
        annotation.coordinate = CLLocationCoordinate2D(latitude: self.lat, longitude: self.lon)
        view.addAnnotation(annotation)
        return view
    }
    
    func updateUIView(_ uiView: MKMapView, context: UIViewRepresentableContext<AnimationMapView>) {
        print(uiView.annotations)
        
        // MapAnimationViewの座標が更新された場合、アニメーションで移動させる
        if uiView.annotations.count > 0{
            let annotation = uiView.annotations[0] as! MKPointAnnotation
            let targetPosition = CLLocationCoordinate2D(latitude: self.lat, longitude: self.lon)
            UIView.animate(withDuration: 4, animations: {
                annotation.coordinate = targetPosition
               }, completion: nil)
        }
    }
}

備考

swiftUIのアニメーション機能を利用してUIKitを動かそうとしたができませんでした...

3
3
0

Register as a new user and use Qiita more conveniently

  1. You get articles that match your needs
  2. You can efficiently read back useful information
  3. You can use dark theme
What you can do with signing up
3
3

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?