Mapを使ってると、ルート描きたいなーって思うことありますよね?
今回はこの記事のほぼ丸パクリです...
https://www.iostutorialjunction.com/2018/03/draw-route-on-apple-map-or-mapkit-tutorial-in-swift4.html
記事ではアメリカなので、対抗して東京駅-大阪駅間でルート書いてみました。
あとは私なりにですが少しコードの解説してみます。ちなみにswift4.2です。
1.ロケーションの設定
これはわかりやすいですね。東京駅と大阪駅の緯度経度をCoordinateに与えています。
let sourceLocation = CLLocationCoordinate2D(latitude:35.681464, longitude: 139.767052)
let destinationLocation = CLLocationCoordinate2D(latitude:34.702741, longitude: 135.495929)
2.出発地/到着地にPinを置く
annotationの設定です。いわゆるマップ上のPINの設定です。
今回はカスタムクラスにタイトルとlocationの情報を与えてを追加しています
// add annotation
let sourcePin = customPin(pinTitle: "Tokyo Station", pinSubTitle: "", location: sourceLocation)
let destinationPin = customPin(pinTitle: "Osaka Station", pinSubTitle: "", location: destinationLocation)
self.mapView.addAnnotation(sourcePin)
self.mapView.addAnnotation(destinationPin)
3.MKPlacemarkの設定
ここは僕も詳しくわかっていないのですが、公式を見るとspecified coordinateって書いてあるので、
経路探索するための情報なのかと思います。
https://developer.apple.com/documentation/mapkit/mkplacemark
let sourcePlaceMark = MKPlacemark(coordinate: sourceLocation)
let destinationPlaceMark = MKPlacemark(coordinate: destinationLocation)
4.経路探索→経路を設定。そして縮尺を設定
ここでメインのMKDirectionsが出てきます。
先ほど設定したMKPlacemarkを与えて経路探索のリクエストを投げます。
経路が帰ってきたら、addOverlayで経路情報をMapに追加します。
その後ルートが入る範囲で縮尺を設定します
最後にdelegateをお忘れなく..
let directionRequest = MKDirections.Request()
directionRequest.source = MKMapItem(placemark: sourcePlaceMark)
directionRequest.destination = MKMapItem(placemark: destinationPlaceMark)
directionRequest.transportType = .automobile
let directions = MKDirections(request: directionRequest)
directions.calculate { (response, error) in
guard let directionResonse = response else {
if let error = error {
print("we have error getting directions==\(error.localizedDescription)")
}
return
}
// ルートを追加
let route = directionResonse.routes[0]
self.mapView.addOverlay(route.polyline, level: .aboveRoads)
// 縮尺を設定
let rect = route.polyline.boundingMapRect
self.mapView.setRegion(MKCoordinateRegion(rect), animated: true)
}
//set delegate for mapview
self.mapView.delegate = self
ちなみに帰ってくるルートは複数あるようで、全て表示したい場合はroutesをaddすれば表示できそうです。
(routesがどんな順番で帰ってくるのかイマイチわかりませんが...)
5.ルートの描画
最後に描画の処理をdelegateメソッド内に描きます
これはなんとなくでも読めるかもしれませんが線の太さと色を指定しています。
//MARK:- MapKit delegates
func mapView(_ mapView: MKMapView, rendererFor overlay: MKOverlay) -> MKOverlayRenderer {
let renderer = MKPolylineRenderer(overlay: overlay)
renderer.strokeColor = UIColor.blue
renderer.lineWidth = 4.0
return renderer
}
とここまで書いたものをgithubに公開したのでよかったら参考してください。
https://github.com/entaku19890818/map
これで大阪駅まで迷わずいけますね。
え、新幹線使えよって?