MapKitとCoreLocationで現在地の地図を表示する

Xcode 9.2 / Swift 4.0.3

現在地情報はシミュレーターのデフォルト値を使用しています。

MapKit

地図を表示する

f:id:tid-a24:20180310130658p:plain:w240

import UIKit
import MapKit

class ViewController: UIViewController {
    lazy var mapView: MKMapView = {
        let mapView = MKMapView(frame: view.frame)
        return mapView
    }()

    override func viewDidLoad() {
        super.viewDidLoad()
        view.addSubview(mapView)
    }
}

CoreLocation

現在地を取得

info.plistに権限設定を追加します。 Valueには使用用途を説明する文章を入力する必要があります。 ここに入力した文字列はユーザーに表示されます。

f:id:tid-a24:20180313004449p:plain

権限設定 説明
NSLocationWhenInUseUsageDescription 使用中のみ許可
NSLocationAlwaysAndWhenInUseUsageDescription 常に許可、使用中のみ許可
NSLocationAlwaysUsageDescription 常に許可

iOS11 から使用中のみ許可(NSLocationWhenInUseUsageDescription)のサポートが必須となっているので上2つのどちらかを使うことになると思います。 使用中のみ許可と常に許可の両方をサポートして、それぞれ違う説明文を表示する場合だけNSLocationWhenInUseUsageDescriptionNSLocationAlwaysUsageDescriptionを指定します。

import UIKit
import MapKit
import CoreLocation

class ViewController: UIViewController {
    let locationManager = CLLocationManager()

    override func viewDidLoad() {
        super.viewDidLoad()
        locationManager.delegate = self
    }
}

extension ViewController: CLLocationManagerDelegate {
    func locationManager(_ manager: CLLocationManager, didChangeAuthorization status: CLAuthorizationStatus) {
        switch status {
        case .notDetermined:
            locationManager.requestWhenInUseAuthorization()
        case .authorizedWhenInUse:
            locationManager.startUpdatingLocation()
        default:
            break
        }
    }

    func locationManager(_ manager: CLLocationManager, didUpdateLocations locations: [CLLocation]) {
        // locationsに現在地が入っています
    }
}

MapKit + CoreLocation

現在地の地図を拡大して表示する

f:id:tid-a24:20180310130520p:plain:w240

func locationManager(_ manager: CLLocationManager, didUpdateLocations locations: [CLLocation]) {
    if let coordinate = locations.last?.coordinate {
        // 現在地を拡大して表示する
        let span = MKCoordinateSpan(latitudeDelta: 0.01, longitudeDelta: 0.01)
        let region = MKCoordinateRegion(center: coordinate, span: span)
        mapView.region = region
    }
}

MKCoordinateSpanに指定しているlatitudeDelta / latitudeDelta の値を小さくするほど拡大されます。

地図上の現在地にピンをつける

f:id:tid-a24:20180310131006p:plain:w240

func locationManager(_ manager: CLLocationManager, didUpdateLocations locations: [CLLocation]) {
    if let coordinate = locations.last?.coordinate {
        // ピンをつける
        let pin = MKPointAnnotation()
        pin.coordinate = coordinate
        mapView.addAnnotation(pin)

        // 現在地を拡大して表示する
        let span = MKCoordinateSpan(latitudeDelta: 0.01, longitudeDelta: 0.01)
        let region = MKCoordinateRegion(center: coordinate, span: span)
        mapView.region = region
    }
}