LoginSignup
0
4

More than 3 years have passed since last update.

Swift MkMapViewで地図アプリ作成してみた(23) ルートを探索する

Last updated at Posted at 2020-05-04

記事一覧

Swift MkMapViewで地図アプリ作成してみた(記事一覧)

ルートを探索する

ルートを探索した結果、ポリラインが取得できるので、線を引く。
また、地図をルート全体が表示できるスケールに変更する。

ルートを探索する
// 探索結果のポリライン
var routePolyLine: MKPolyline!

// ルート探索
public func routeSearch() {
    // 出発地(現在位置)
    let sourcePlaceMark = MKPlacemark(coordinate: mapView.userLocation.coordinate)
    // 目的地(tapRoutePoint)
    let destinationPlaceMark = MKPlacemark(coordinate: tapRoutePoint)

    // 出発地と目的地をMKDirectionsのリクエストに設定する
    let directionRequest = MKDirections.Request()
    directionRequest.source = MKMapItem(placemark: sourcePlaceMark)
    directionRequest.destination = MKMapItem(placemark: destinationPlaceMark)

    // 徒歩のルートを設定する
    directionRequest.transportType = .walking

    // ルート探索を実行する
    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
        }
        // 成功の場合、mainスレッドで処理する
        DispatchQueue.main.async {
            // 探索結果のポリラインの線を引く
            let route = directionResonse.routes[0]
            self.routePolyLine = route.polyline
            self.routePolyLine.subtitle = "route"
            self.mapView.addOverlay(self.routePolyLine)

            // 地図をルート全体が表示できるスケールに変更する
            let rect = route.polyline.boundingMapRect
            self.mapView.setRegion(MKCoordinateRegion(rect), animated: true)
        }
    }
}

addOverlayで塗り潰す線の太さと色を設定する

ルート線の場合は、太さ6、緑色の線を引く。

addOverlayで塗り潰す線の太さと色を設定する
    // addOverlayした際に呼ばれるデリゲートメソッド
    func mapView(_ mapView: MKMapView, rendererFor overlay: MKOverlay) -> MKOverlayRenderer {
        // rendererを生成.
        let myPolyLineRendere: MKPolylineRenderer = MKPolylineRenderer(overlay: overlay)

        if ("route" == overlay.subtitle) { // subtitleで指定した文字列
            // 線の太さを指定.
            myPolyLineRendere.lineWidth = 6
            // 線の色を指定.
            myPolyLineRendere.strokeColor = UIColor.green
        }
        else {
            // 線の太さを指定.
            myPolyLineRendere.lineWidth = 5
            // 線の色を指定.
            myPolyLineRendere.strokeColor = UIColor.blue
        }

        return myPolyLineRendere
    }
0
4
0

Register as a new user and use Qiita more conveniently

  1. You get articles that match your needs
  2. You can efficiently read back useful information
  3. You can use dark theme
What you can do with signing up
0
4