【Xcode/Swift】MapViewを使って現在地を取得&表示しよう

今回はMapViewを使って現在地を表示するシンプルなアプリを作ります。

Storyboard


コーディング

import UIKit
import MapKit

class HomeViewController: UIViewController {
    @IBOutlet private weak var myLocationButton: UIButton!
    @IBOutlet private weak var mapKitView: MKMapView!

    private let locationManager = CLLocationManager()

    override func viewDidLoad() {
        super.viewDidLoad()
        setupMapView()
    }

    private func setupMapView() {
        locationManager.delegate = self
        locationManager.desiredAccuracy = kCLLocationAccuracyBest
        locationManager.requestWhenInUseAuthorization()
    }

    @IBAction func showMyLocationAction(_ sender: Any) {
        locationManager.requestLocation()
    }

}

extension HomeViewController: CLLocationManagerDelegate {
    func locationManager(_ manager: CLLocationManager, didUpdateLocations locations: [CLLocation]) {
        guard let location = locations.last else { return }
        CLGeocoder().reverseGeocodeLocation(location, completionHandler: { (placemarks, error) in
            if let error = error {
                print("reverseGeocodeLocation Failed: \(error.localizedDescription)")
                return
            }
            if let placemark = placemarks?.first {
                var locationInformation = ""
                locationInformation += "Latitude: \(location.coordinate.latitude)\n"
                locationInformation += "Longitude: \(location.coordinate.longitude)\n\n"
                locationInformation += "Country: \(placemark.country ?? "")\n"
                locationInformation += "State/Province: \(placemark.administrativeArea ?? "")\n"
                locationInformation += "City: \(placemark.locality ?? "")\n"
                locationInformation += "PostalCode: \(placemark.postalCode ?? "")\n"
                locationInformation += "Name: \(placemark.name ?? "")"
            }
        })

        let coordinateRegion = MKCoordinateRegion(center: location.coordinate, latitudinalMeters: 500, longitudinalMeters: 500)
        mapKitView.setRegion(coordinateRegion, animated: true)

        let pointAnnotation = MKPointAnnotation()
        pointAnnotation.title = "ここにいるよ!"
        pointAnnotation.coordinate = location.coordinate

        mapKitView.removeAnnotations(mapKitView.annotations)
        mapKitView.addAnnotation(pointAnnotation)
    }

    func locationManager(_ manager: CLLocationManager, didFailWithError error: Error) {
        print("Error: \(error.localizedDescription)")
    }

}

ひとくちメモ

Appleでは位置情報等を扱う時は許可設定が必須なので忘れずに行っておきましょう。

Info.plist内で以下二つを追加

Privacy – Location Usage Description
Privacy – Location When In Use Usage Description

まとめ

今回は以上です、地図を使ったアプリを作りたい方はぜひ参考にしてみてください!