LoginSignup
1
3

SwiftUI の MapKit で画面をタップした場所の緯度・経度を取得する (iOS17〜)

Last updated at Posted at 2023-10-23

概要

iOS17 から MapReader を使って、SwiftUI のマップで表示している画面上の位置を緯度・経度に変換することができるようになりました。

取得方法

SwiftUI の View 上でタップした位置の座標を、緯度・経度に変換するコードは下記の通りです。GeometoryReader で View を囲むのと同じように、 MapReader で Map を囲みます。あとは convert メソッドで画面の座標を、緯度経度の座標に変換します。

サンプルコード

swift
MapReader { reader in
                    Map()
                        .onTapGesture(perform: { screenLocation in
                            guard let location = reader.convert(screenLocation, from: .local) else { return }
                            print("tapped point: ", location)
                        })
                }

かんたんですね!

おわりに

iOS16 までは MapKit を SwiftUI で扱う場合に、マップ上の画面の座標を、緯度・経度に変換する標準の方法はありませんでした。そのため、UIKit の MapKit に頼らざるを得ない側面がありましたが、iOS17 になり、 SwiftUI 対応も進んできて実用領域に入った感じがして嬉しいですね!

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