LoginSignup
1
2

More than 3 years have passed since last update.

Swift MkMapViewで地図アプリ作成してみた(09)- ロングタップした位置と現在位置の距離を求める

Last updated at Posted at 2019-02-23

記事一覧

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

ロングタップした位置と現在位置の距離を求める

  1. 2点間の距離を求める関数を作成する

    CLLocationオブジェクトのdistance関数で2点間の距離(m)を算出できる。

    ViewController.swift:2点間の距離を求める関数を作成する
    // 2点間の距離(m)を算出する
    func calcDistance(_ a: CLLocationCoordinate2D, _ b: CLLocationCoordinate2D) -> CLLocationDistance {
        // CLLocationオブジェクトを生成
        let aLoc: CLLocation = CLLocation(latitude: a.latitude, longitude: a.longitude)
        let bLoc: CLLocation = CLLocation(latitude: b.latitude, longitude: b.longitude)
        // CLLocationオブジェクトのdistanceで2点間の距離(m)を算出
        let dist = bLoc.distance(from: aLoc)
        return dist
    }
    
  2. ロングタップを検出した時に(1.)で作成した関数をCallする

    Swift MkMapViewで地図アプリ作成してみた(08)で取得したロングタップした位置と、現在位置の2点間の距離(m)を算出する。

    位置情報 変数 
    現在位置 mapView.userLocation.coordinate
    ロングタップした位置 center
    ViewController.swift:calcDistance関数をCallする
    // UILongPressGestureRecognizerのdelegate:ロングタップを検出する
    @IBAction func mapViewDidLongPress(_ sender: UILongPressGestureRecognizer) {
        // ロングタップ開始
        if sender.state == .began {
        }
        // ロングタップ終了(手を離した)
        else if sender.state == .ended {
            // タップした位置(CGPoint)を指定してMkMapView上の緯度経度を取得する
            let tapPoint = sender.location(in: view)
            let center = mapView.convert(tapPoint, toCoordinateFrom: mapView)
    
            let lonStr = center.longitude.description
            let latStr = center.latitude.description
            print("lon : " + lonStr)
            print("lat : " + latStr)
    
            // 現在位置とタッウプした位置の距離(m)を算出する
            let distance = calcDistance(mapView.userLocation.coordinate, center)
            print("distance : " + distance.description)
        }
    }
    

    記事一覧

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

1
2
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
1
2