2016-08-02 4 views
1

enter image description here Я создал маршрут с несколькими аннотациями. Я хочу отобразить текст между аннотациями, которые точно так же, как приложенные снимки экрана.Как отображать время по маршруту как карты Google

Может ли кто-нибудь помочь, пожалуйста?

Благодаря

+0

Прикрепленное изображение. Мне нужно показать время на MKPolyline, которое совпадает с прикрепленным изображением. Может у вас есть идея? –

+0

Вы пробовали просто добавить еще одну аннотацию в определенном месте? – Wain

+0

@ Спасибо за ответ. Да, я попытался добавить еще одну аннотацию. но после этого viewForAnnotation вызывает как аннотации (первый набор аннотаций, так и аннотацию midpoint) и дает неожиданный результат. –

ответ

0

Я пытался что-то, который будет показывать расстояние между двумя аннотацию, но не тогда, когда вы нажмете на MKPolylineOverlay. Еще одна важная вещь: я не поддерживаю никаких стандартов.

Вот моя структура контроллера.

import UIKit 
import MapKit 

class RouteViewController: UIViewController, MKMapViewDelegate { 

    @IBOutlet weak var mapView: MKMapView! 

    //Rest of the code see below 
} 

Прежде всего я добавить аннотацию к карте в методе viewDidLoad делегата, как показано ниже.

override func viewDidLoad() { 
    super.viewDidLoad() 
    self.mapView.delegate = self 

    let annotation1 = MKPointAnnotation() 
    annotation1.title = "Times Square" 
    annotation1.coordinate = CLLocationCoordinate2D(latitude: 40.759011, longitude: -73.984472) 

    let annotation2 = MKPointAnnotation() 
    annotation2.title = "Empire State Building" 
    annotation2.coordinate = CLLocationCoordinate2D(latitude: 40.748441, longitude: -73.985564) 

    let annotation3 = MKPointAnnotation() 
    annotation3.title = "Some Point" 
    annotation3.coordinate = CLLocationCoordinate2D(latitude: 40.7484, longitude: -73.97) 

    let arrayOfPoints = [ annotation1, annotation2, annotation3] 
    self.mapView.addAnnotations(arrayOfPoints) 
    self.mapView.centerCoordinate = annotation2.coordinate 

    for (index, annotation) in arrayOfPoints.enumerate() { 
     if index < (arrayOfPoints.count-1) { 
      //I am taking the two consecutive annotation and performing the routing operation. 
      self.directionHandlerMethod(annotation.coordinate, ePoint: arrayOfPoints[index+1].coordinate) 
     } 
    } 
} 

В directionHandlerMethod, я совершаю фактический запрос о направлении, как показано ниже,

func directionHandlerMethod(sPoint: CLLocationCoordinate2D, ePoint: CLLocationCoordinate2D) { 
    let sourcePlacemark = MKPlacemark(coordinate: sPoint, addressDictionary: nil) 
    let destinationPlacemark = MKPlacemark(coordinate: ePoint, addressDictionary: nil) 
    let sourceMapItem = MKMapItem(placemark: sourcePlacemark) 
    let destinationMapItem = MKMapItem(placemark: destinationPlacemark) 

    let directionRequest = MKDirectionsRequest() 
    directionRequest.source = sourceMapItem 
    directionRequest.destination = destinationMapItem 
    directionRequest.transportType = .Automobile 
    let directions = MKDirections(request: directionRequest) 
    directions.calculateDirectionsWithCompletionHandler { 
     (response, error) -> Void in 
     guard let response = response else { 
      if let error = error { 
       print("Error: \(error)") 
      } 
      return 
     } 
     //I am assuming that it will contain one and only one result so I am taking that one passing to addRoute method 
     self.addRoute(response.routes[0]) 
    } 
} 

Далее я добавляю по ломаной линии маршрута на карте в методе addRoute, как показано ниже,

func addRoute(route: MKRoute) { 
    let polyline = route.polyline 

    //Here I am taking the centre point on the polyline and placing an annotation by giving the title as 'Route' and the distance in the subtitle 
    let annoatation = MKPointAnnotation() 
    annoatation.coordinate = MKCoordinateForMapPoint(polyline.points()[polyline.pointCount/2]) 
    annoatation.title = "Route" 
    let timeInMinute = route.expectedTravelTime/60 
    let distanceString = String.localizedStringWithFormat("%.2f %@", timeInMinute, timeInMinute>1 ? "minutes" : "minute") 
    annoatation.subtitle = distanceString 
    self.mapView.addAnnotation(annoatation) 

    self.mapView.addOverlay(polyline) 
} 

Далее Я внедряю rendere rForOverlay метод делегата, как показано ниже,

func mapView(mapView: MKMapView, rendererForOverlay overlay: MKOverlay) -> MKOverlayRenderer { 
    let renderer = MKPolylineRenderer(overlay: overlay) 
    renderer.strokeColor = UIColor.blueColor() 
    renderer.lineWidth = 2 
    renderer.lineCap = .Butt 
    renderer.lineJoin = .Round 
    return renderer 
} 

Следующая один является важным один метод делегата, который является viewForAnnotation. Здесь я делаю некоторые вещи, например, помещая ярлык вместо аннотации, как показано ниже:

func mapView(mapView: MKMapView, viewForAnnotation annotation: MKAnnotation) -> MKAnnotationView? { 
    if annotation.title != nil && annotation.title!! == "Route" { 
     let label = UILabel() 
     label.adjustsFontSizeToFitWidth = true 
     label.backgroundColor = UIColor.whiteColor() 
     label.minimumScaleFactor = 0.5 
     label.frame = CGRect(x: 0, y: 0, width: 100, height: 30) 
     label.text = annotation.subtitle ?? "" 
     let view = MKAnnotationView() 
     view.addSubview(label) 
     return view 
    } 
    return nil 
} 
Смежные вопросы