Swift를 사용하여 현재 위치의 취득과 지도를 바늘로 설정합니다

개요


스위프트에서 현재 위치를 확보하고 지도에 핀을 꽂는 방법이다.
 1. Info.pist에 위치 정보에 대한 액세스 허용 추가(N S L oca t i o n When InUseUsageDescription)
 2. MKMapView의 전체 붙여넣기를 시작하여 startUpdating Location()에서 위치 정보를 가져옵니다.
 3. CLGeocoder로 주소에서 위도 경도를 가져오고addannotation()로 핀을 세로로
다른 기사도 찾아봤지만 바로 쓸 수 있는 코드가 없어 미리 공유했다.

컨디션


Swift 4
Xcode 10.1

결실




코드

import UIKit
import MapKit
import CoreLocation

struct Annotation {
    let address: String
    let title: String?
    let subtitle: String?
}

class MapViewController: UIViewController {

    @IBOutlet weak var mapView: MKMapView!

    let locationManager = CLLocationManager()

    override func viewDidLoad() {
        super.viewDidLoad()

        configureSubviews()
    }

    override func viewDidAppear(_ animated: Bool) {
        super.viewDidAppear(animated)

        startUpdatingLocation()

        let annotation = Annotation(
            address: "神奈川県横浜市青葉区青葉台1-7-3",
            title: "青葉台駅です",
            subtitle: "田園都市線はいつも激混み")
        add(with: annotation)
    }

    private func add(with annotation: Annotation) {
        CLGeocoder().geocodeAddressString(annotation.address) { [weak self] (placeMarks, error) in
            guard let placeMark = placeMarks?.first,
                let latitude = placeMark.location?.coordinate.latitude,
                let longitude = placeMark.location?.coordinate.longitude else { return }

            let point = MKPointAnnotation()
            point.coordinate = CLLocationCoordinate2DMake(latitude, longitude)
            point.title = annotation.title
            point.subtitle = annotation.subtitle
            self?.mapView.addAnnotation(point)
        }
    }

    private func startUpdatingLocation() {
        switch CLLocationManager.authorizationStatus() {
        case .notDetermined:
            locationManager.requestWhenInUseAuthorization()
        default:
            break
        }
        locationManager.startUpdatingLocation()
    }

    private func configureSubviews() {
        locationManager.delegate = self
        locationManager.desiredAccuracy = kCLLocationAccuracyBest
        locationManager.distanceFilter = 100
        locationManager.startUpdatingLocation()

        mapView.delegate = self
        mapView.mapType = .standard
        mapView.userTrackingMode = .follow
        mapView.userTrackingMode = .followWithHeading
    }
}


// MARK: - MKMapViewDelegate
extension MapViewController: MKMapViewDelegate {
}


// MARK: - CLLocationManagerDelegate
extension MapViewController: CLLocationManagerDelegate {
    func locationManager(_ manager: CLLocationManager, didUpdateLocations locations: [CLLocation]) {
        print("位置情報の取得に成功しました")
    }

    func locationManager(_ manager: CLLocationManager, didFailWithError error: Error) {
        let alert = UIAlertController(title: nil, message: "位置情報の取得に失敗しました", preferredStyle: .alert)
        alert.addAction(UIAlertAction.init(title: "OK", style: .default, handler: { (_) in
            self.dismiss(animated: true, completion: nil)
        }))
        present(alert, animated: true, completion: nil)
    }
}

좋은 웹페이지 즐겨찾기