LoginSignup
11
12

More than 3 years have passed since last update.

Swift MkMapViewで地図アプリ作成してみた(03)- 現在位置を地図の中心にする

Last updated at Posted at 2019-02-17

記事一覧

Swift MkMapViewで地図アプリ作成してみた(記事一覧)

Viewのload時に地図を初期化する

  1. 地図の初期化関数を作成する

    地図の初期化関数
        func initMap() {
            // 縮尺を設定
            var region:MKCoordinateRegion = mapView.region
            region.span.latitudeDelta = 0.02
            region.span.longitudeDelta = 0.02
            mapView.setRegion(region,animated:true)
    
            // 現在位置表示の有効化
            mapView.showsUserLocation = true
            // 現在位置設定(デバイスの動きとしてこの時の一回だけ中心位置が現在位置で更新される)
            mapView.userTrackingMode = .follow
        }
    
    設定値 振る舞い 
    .follow 現在位置のみ更新する
    .followWithHeading 現在位置と方向(ヘディングアップ)を更新する
    .none 更新しない
  2. Viewのload時に地図の初期化関数をCallする

    Viewのload時に地図の初期化関すをCallする
        override func viewDidLoad() {
            super.viewDidLoad()
            // Do any additional setup after loading the view, typically from a nib.
    
            // 地図の初期化
            initMap()
        }
    

現在位置が更新される度に地図の中心位置を変更する

  1. 地図の中心位置の変更関数を作成する

    地図の中心位置の更新関数
        func updateCurrentPos(_ coordinate:CLLocationCoordinate2D) {
            var region:MKCoordinateRegion = mapView.region
            region.center = coordinate
            mapView.setRegion(region,animated:true)
        }
    
  2. 現在位置の更新時に地図の中心位置の変更関数をCallする

    現在位置の更新時に地図の中心位置の変更関数をCallする
        // CLLocationManagerのdelegate:現在位置取得
        func locationManager(_ manager: CLLocationManager, didUpdateLocations locations:[CLLocation]) {
            updateCurrentPos((locations.last?.coordinate)!)
        }
    
  3. ▶︎を押してPCシミュレータを起動する。
    Device.png

補足

  • 以下の様にした方が現在位置更新がカクカクせずにスムーズになる。

    補足
        // CLLocationManagerのdelegate:現在位置取得
        func locationManager(_ manager: CLLocationManager, didUpdateLocations locations:[CLLocation]) {
            // updateCurrentPos((locations.last?.coordinate)!)
            mapView.userTrackingMode = .follow
        }
    

記事一覧

Swift MkMapViewで地図アプリ作成してみた(記事一覧)

11
12
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
11
12