Obtener información de ruta

Sigue esta guía para configurar tu app y obtener los tiempos, las distancias y los tramos de la ruta actual.

Descripción general

Para obtener información sobre la ruta actual, obtén la propiedad correspondiente en la instancia de navigator:

Consulta el código

Logrando tiempo para el próximo destino

Para obtener el tiempo hasta el próximo destino, llama a timeToNextDestination(). Se muestra un valor NSTimeInterval. En el siguiente ejemplo, se muestra cómo registrar el tiempo hasta el siguiente destino:

Swift

if let navigator = mapView.navigator {
  let time = navigator.timeToNextDestination
  let minutes = floor(time/60)
  let seconds = round(time - minutes * 60)
  NSLog("Time to next destination: %.0f:%.0f", minutes, seconds)
}

Objective‑C

NSTimeInterval time = _mapView.navigator.timeToNextDestination;
int minutes = floor(time/60);
int seconds = round(time - minutes * 60);
NSLog(@"%@", [NSString stringWithFormat:@"Time to next destination: %i:%i.", minutes, seconds]);

Obteniendo distancia para llegar al próximo destino

Para obtener la distancia al próximo destino, llama a distanceToNextDestination(). Se muestra un valor CLLocationDistance. Las unidades se especifican en metros.

Swift

if let navigator = mapView.navigator {
  let distance = navigator.distanceToNextDestination
  let miles = distance * 0.00062137
  NSLog("Distance to next destination: %.2f miles.", miles)
}

Objective‑C

CLLocationDistance distance = _mapView.navigator.distanceToNextDestination;
double miles = distance * 0.00062137;
NSLog(@"%@", [NSString stringWithFormat:@"Distance to next destination: %.2f.", miles]);

Cómo obtener las condiciones de tráfico para el próximo destino

Para obtener un valor que indique el flujo del tráfico al siguiente destino, llama a delayCategoryToNextDestination. Este parámetro muestra GMSNavigationDelayCategory. En el siguiente ejemplo, se muestra cómo evaluar el resultado y registrar un mensaje de tráfico:

Swift

if let navigator = mapView.navigator {
  // insert sample for evaluating traffic value
  let delay = navigator.delayCategoryToNextDestination
  let traffic = "unavailable"
  switch delay {
    case .noData:
      traffic = "unavailable"
    case .heavy:
      traffic = "heavy"
    case .medium:
      traffic = "moderate"
    case .light:
      traffic = "light"
    default:
      traffic = "unavailable"
  }
  print("Traffic is \(traffic).")
}

Objective‑C

GMSNavigationDelayCategory delay = mapView.navigator.delayCategoryToNextDestination;
NSString *traffic = @"";

switch (delayCategory) {
    case GMSNavigationDelayCategoryNoData:
      traffic = @"No Data";
      break;
    case GMSNavigationDelayCategoryHeavy:
      traffic = @"Heavy";
      break;
    case GMSNavigationDelayCategoryMedium:
      traffic = @"Medium";
      break;
    case GMSNavigationDelayCategoryLight:
      traffic = @"Light";
      break;
    default:
      NSLog(@"Invalid delay category: %zd", delayCategory);
 }

NSLog(@"%@", [NSString stringWithFormat:@"Traffic is %@.", traffic]);

Obtener información sobre el segmento actual

Para obtener información sobre el tramo de la ruta actual, llama a currentRouteLeg. Esto muestra una instancia de GMSRouteLeg, desde la cual puedes obtener:

  • El destino de la pierna.
  • La coordenada final de la etapa.
  • El trazado que contiene las coordenadas que conforman el tramo de la ruta.

En el siguiente ejemplo, se muestra cómo registrar el título y las coordenadas de latitud y longitud para el siguiente segmento de la ruta:

Swift

if let navigator = mapView.navigator {
  let currentLeg = navigator.currentRouteLeg
  let nextDestination = currentLeg?.destinationWaypoint?.title
  let lat = currentLeg?.destinationCoordinate.latitude.description
  let lng = currentLeg?.destinationCoordinate.longitude.description
  NSLog(nextDestination! + ", " + lat! + "/" + lng!)
}

Objective‑C

GMSRouteLeg *currentSegment = _mapView.navigator.currentRouteLeg;
NSString *nextDestination = currentSegment.destinationWaypoint.title;
CLLocationDegrees lat = currentSegment.destinationCoordinate.latitude;
CLLocationDegrees lng = currentSegment.destinationCoordinate.longitude;
NSLog(@"%@", [NSString stringWithFormat:@"%@, %f/%f", nextDestination, lat, lng]);

Obtener la ruta más reciente

Para obtener la ruta recorrida más recientemente, llama a traveledPath. Se mostrará una instancia de GMSPath que se simplificó para quitar los puntos redundantes (por ejemplo, convertir puntos colineales consecutivos en un solo segmento de línea). Esta ruta estará vacía hasta que comiences la guía. En el siguiente ejemplo, se muestra cómo obtener la ruta recorrida más recientemente:

Swift

if let navigator = mapView.navigator {
  let latestPath = navigator.traveledPath
  if latestPath.count() > 0 {
    let begin: CLLocationCoordinate2D = latestPath.coordinate(at: 0)
    let current: CLLocationCoordinate2D = latestPath.coordinate(at: latestPath.count() - 1)
    print("Path from (\(begin.latitude),\(begin.longitude)) to (\(current.latitude),\(current.longitude))")
  }
}

Objective‑C

GMSPath *latestPath = mapView.navigator.traveledPath;
if (latestPath.count > 0) {
  CLLocationCoordinate2D begin = [latestPath coordinateAtIndex:0];
  CLLocationCoordinate2D current = [latestPath coordinateAtIndex:latestPath.count - 1];
  NSLog(@"Path from %f/%f to %f/%f",
        begin.latitude,
        begin.longitude,
        current.latitude,
        current.longitude);
}