![見出し画像](https://assets.st-note.com/production/uploads/images/78090475/rectangle_large_type_2_25388a7ff0b083ea2bd06278bcd379d7.png?width=1200)
Photo by
yamamoto15
MapViewを使って現在地を表示しよう
マップ機能を取り入れたい時に役立つ知識だと感じたので備忘用に残します。
◉参考記事
それでは実装していきましょう。
1: storyboard上で見た目を作る。上部にボタン、真ん中にMKMapViewを配置
![](https://assets.st-note.com/img/1651981820366-DeoGHGdZnV.png?width=1200)
2: Info.plistを選択して、以下の二つを新規追加する(許可表示のための設定らしいです)
Privacy - Location Usage Description
Privacy - Location When In Use Usage Description
![](https://assets.st-note.com/img/1651981954317-E8i1XLDueO.png?width=1200)
3: ボタンとマップをそれぞれプログラムとつなげる
![](https://assets.st-note.com/img/1651982394266-zySdOx5JN2.png?width=1200)
4: 以下コードをコピペ
import UIKit
import MapKit
class ViewController: UIViewController {
@IBOutlet weak var button: UIButton!
@IBOutlet weak var mapView: MKMapView!
let locationManager = CLLocationManager()
override func viewDidLoad() {
super.viewDidLoad()
setupView()
setupMapView()
}
private func setupView() {
button.layer.cornerRadius = 20.0
}
private func setupMapView() {
locationManager.delegate = self
locationManager.desiredAccuracy = kCLLocationAccuracyBest
locationManager.requestWhenInUseAuthorization()
}
@IBAction func getCurrentLocationTapped(_ sender: Any) {
locationManager.requestLocation()
}
}
extension ViewController: CLLocationManagerDelegate {
func locationManager(_ manager: CLLocationManager, didUpdateLocations locations: [CLLocation]) {
guard let loc = locations.last else { return }
CLGeocoder().reverseGeocodeLocation(loc, completionHandler: {(placemarks, error) in
if let error = error {
print("reverseGeocodeLocation Failed: \(error.localizedDescription)")
return
}
if let placemark = placemarks?[0] {
var locInfo = ""
locInfo = locInfo + "Latitude: \(loc.coordinate.latitude)\n"
locInfo = locInfo + "Longitude: \(loc.coordinate.longitude)\n\n"
locInfo = locInfo + "Country: \(placemark.country ?? "")\n"
locInfo = locInfo + "State/Province: \(placemark.administrativeArea ?? "")\n"
locInfo = locInfo + "City: \(placemark.locality ?? "")\n"
locInfo = locInfo + "PostalCode: \(placemark.postalCode ?? "")\n"
locInfo = locInfo + "Name: \(placemark.name ?? "")"
}
})
let cr = MKCoordinateRegion(center: loc.coordinate, latitudinalMeters: 500, longitudinalMeters: 500)
mapView.setRegion(cr, animated: true)
let pa = MKPointAnnotation()
pa.title = "ここにいるよ!"
pa.coordinate = loc.coordinate
mapView.removeAnnotations(mapView.annotations)
mapView.addAnnotation(pa)
}
func locationManager(_ manager: CLLocationManager, didFailWithError error: Error) {
print("error: \(error.localizedDescription)")
}
}
ここまでできたらビルドをしましょう
![](https://assets.st-note.com/img/1651982486774-3dzdtkhSXX.png)
![](https://assets.st-note.com/production/uploads/images/78090318/picture_pc_b4a3052e40cf873750c6fe1959b90e71.gif)
実機だときちんと今自分がいる場所を示すはずです
今回は以上です。
この記事が気に入ったらサポートをしてみませんか?