Mantenha tudo organizado com as coleções
Salve e categorize o conteúdo com base nas suas preferências.
Use este guia para permitir que seu app ouça e responda a vários eventos
que mudam à medida que um usuário navega por um trajeto. Este guia não aborda a definição de uma rota, apenas a resposta a eventos ao longo dela.
Visão geral
O SDK Navigation para iOS oferece listeners
associados à localização do usuário e às condições ao longo da rota, além de
dados importantes de tempo e distância. No controlador de visualização do mapa, seu app
precisa adotar os protocolos para estes listeners:
GMSRoadSnappedLocationProviderListener
e
GMSNavigatorListener.
Esta lista mostra os métodos de listener disponíveis para eventos de navegação:
Mostrar/ocultar o código Swift
de um listener de eventos.
/**Copyright2020GoogleInc.Allrightsreserved.**LicensedundertheApacheLicense,Version2.0(the"License");*youmaynotusethisfileexceptincompliancewiththeLicense.*YoumayobtainacopyoftheLicenseat**http://www.apache.org/licenses/LICENSE-2.0**Unlessrequiredbyapplicablelaworagreedtoinwriting,software*distributedundertheLicenseisdistributedonan"AS IS"BASIS,*WITHOUTWARRANTIESORCONDITIONSOFANYKIND,eitherexpressorimplied.*SeetheLicenseforthespecificlanguagegoverningpermissionsand*limitationsundertheLicense.*/importGoogleNavigationimportUIKitclassViewController:UIViewController,GMSNavigatorListener,GMSRoadSnappedLocationProviderListener{varmapView:GMSMapView!varlocationManager:CLLocationManager!overridefuncloadView(){locationManager=CLLocationManager()letcamera=GMSCameraPosition.camera(withLatitude:47.67,longitude:-122.20,zoom:14)mapView=GMSMapView.map(withFrame:CGRect.zero,camera:camera)//AddlistenersforGMSNavigatorandGMSRoadSnappedLocationProvider.mapView.navigator?.add(self)mapView.roadSnappedLocationProvider?.add(self)//Setthetimeupdatethreshold(seconds)anddistanceupdatethreshold(meters).mapView.navigator?.timeUpdateThreshold=10mapView.navigator?.distanceUpdateThreshold=100//Showthetermsandconditions.letcompanyName="Ride Sharing Co."GMSNavigationServices.showTermsAndConditionsDialogIfNeeded(withCompanyName:companyName){termsAcceptediniftermsAccepted{//Enablenavigationiftheuseracceptstheterms.self.mapView.isNavigationEnabled=true//Requestauthorizationtouselocationservices.self.locationManager.requestAlwaysAuthorization()//Requestauthorizationforalertnotificationswhichdeliverguidanceinstructions//inthebackground.UNUserNotificationCenter.current().requestAuthorization(options:[.alert]){granted,errorin//Handledeniedauthorizationtodisplaynotifications.if!granted||error!=nil{print("Authorization to deliver notifications was rejected.")}}}else{//Handlethecasewhentheuserrejectsthetermsandconditions.}}view=mapViewmakeButton()}//Createarouteandstartguidance.@objcfuncstartNav(){vardestinations=[GMSNavigationWaypoint]()destinations.append(GMSNavigationWaypoint.init(placeID:"ChIJnUYTpNASkFQR_gSty5kyoUk",title:"PCC Natural Market")!)destinations.append(GMSNavigationWaypoint.init(placeID:"ChIJJ326ROcSkFQRBfUzOL2DSbo",title:"Marina Park")!)mapView.navigator?.setDestinations(destinations){routeStatusinguardrouteStatus==.OKelse{print("Handle route statuses that are not OK.")return}self.mapView.navigator?.isGuidanceActive=trueself.mapView.cameraMode=.followingself.mapView.locationSimulator?.simulateLocationsAlongExistingRoute()}mapView.roadSnappedLocationProvider?.startUpdatingLocation()}//Listenertohandlecontinuouslocationupdates.funclocationProvider(_locationProvider:GMSRoadSnappedLocationProvider,didUpdatelocation:CLLocation){print("Location: \(location.description)")}//Listenertohandlespeedingevents.funcnavigator(_navigator:GMSNavigator,didUpdateSpeedingPercentagepercentageAboveLimit:CGFloat){print("Speed is \(percentageAboveLimit) above the limit.")}//Listenertohandlearrivalevents.funcnavigator(_navigator:GMSNavigator,didArriveAtwaypoint:GMSNavigationWaypoint){print("You have arrived at: \(waypoint.title)")mapView.navigator?.continueToNextDestination()mapView.navigator?.isGuidanceActive=true}//Listenerforroutechangeevents.funcnavigatorDidChangeRoute(_navigator:GMSNavigator){print("The route has changed.")}//Listenerfortimetonextdestination.funcnavigator(_navigator:GMSNavigator,didUpdateRemainingTimetime:TimeInterval){print("Time to next destination: \(time)")}//Delegatefordistancetonextdestination.funcnavigator(_navigator:GMSNavigator,didUpdateRemainingDistancedistance:CLLocationDistance){letmiles=distance*0.00062137print("Distance to next destination: \(miles) miles.")}//Delegatefortrafficupdatestonextdestinationfuncnavigator(_navigator:GMSNavigator,didUpdatedelayCategory:GMSNavigationDelayCategory){print("Delay category to next destination: \(String(describing: delayCategory)).")}//Delegateforsuggestedlightingmodechanges.funcnavigator(_navigator:GMSNavigator,didChangeSuggestedLightingModelightingMode:GMSNavigationLightingMode){print("Suggested lighting mode has changed: \(String(describing: lightingMode))")//Changetothesuggestedlightingmode.mapView.lightingMode=lightingMode}//Addabuttontotheview.funcmakeButton(){//Startnavigation.letnavButton=UIButton(frame:CGRect(x:5,y:150,width:200,height:35))navButton.backgroundColor=.bluenavButton.alpha=0.5navButton.setTitle("Start navigation",for:.normal)navButton.addTarget(self,action:#selector(startNav), for: .touchUpInside)self.mapView.addSubview(navButton)}}
Mostra/oculta o código Objective-C de um listener de eventos.
/* * Copyright 2020 Google Inc. All rights reserved. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */#import "ViewController.h"@importGoogleNavigation;@interfaceViewController()<GMSNavigatorListener,GMSRoadSnappedLocationProviderListener>
@end@implementationViewController{GMSMapView*_mapView;CLLocationManager*_locationManager;}-(void)loadView{_locationManager=[[CLLocationManageralloc]init];GMSCameraPosition*camera=[GMSCameraPositioncameraWithLatitude:47.67longitude:-122.20zoom:14];_mapView=[GMSMapViewmapWithFrame:CGRectZerocamera:camera];// Add listeners for GMSNavigator and GMSRoadSnappedLocationProvider.[_mapView.navigatoraddListener:self];[_mapView.roadSnappedLocationProvideraddListener:self];// Set the time update threshold (seconds) and distance update threshold (meters)._mapView.navigator.timeUpdateThreshold=10;_mapView.navigator.distanceUpdateThreshold=100;// Show the terms and conditions.NSString*companyName=@"Ride Sharing Co.";[GMSNavigationServicesshowTermsAndConditionsDialogIfNeededWithCompanyName:companyNamecallback:^(BOOLtermsAccepted){if(termsAccepted){// Enable navigation if the user accepts the terms._mapView.navigationEnabled=YES;// Request authorization to use location services.[_locationManagerrequestAlwaysAuthorization];}else{// Handle the case when the user rejects the terms and conditions.}}];self.view=_mapView;[selfmakeButton];}// Create a route and initiate navigation.-(void)startNav{NSArray<GMSNavigationWaypoint*>*destinations=@[[[GMSNavigationWaypointalloc]initWithPlaceID:@"ChIJnUYTpNASkFQR_gSty5kyoUk"title:@"PCC Natural Market"],[[GMSNavigationWaypointalloc]initWithPlaceID:@"ChIJJ326ROcSkFQRBfUzOL2DSbo"title:@"Marina Park"]];[_mapView.navigatorsetDestinations:destinationscallback:^(GMSRouteStatusrouteStatus){_mapView.navigator.guidanceActive=YES;_mapView.navigator.sendsBackgroundNotifications=YES;_mapView.cameraMode=GMSNavigationCameraModeFollowing;[_mapView.locationSimulatorsimulateLocationsAlongExistingRoute];}];[_mapView.roadSnappedLocationProviderstartUpdatingLocation];}#pragma mark - GMSNavigatorListener// Listener for continuous location updates.-(void)locationProvider:(GMSRoadSnappedLocationProvider*)locationProviderdidUpdateLocation:(CLLocation*)location{NSLog(@"Location: %@",location.description);}// Listener to handle speeding events.-(void)navigator:(GMSNavigator*)navigatordidUpdateSpeedingPercentage:(CGFloat)percentageAboveLimit{NSLog(@"Speed is %f percent above the limit.",percentageAboveLimit);}// Listener to handle arrival events.-(void)navigator:(GMSNavigator*)navigatordidArriveAtWaypoint:(GMSNavigationWaypoint*)waypoint{NSLog(@"You have arrived at: %@",waypoint.title);[_mapView.navigatorcontinueToNextDestination];_mapView.navigator.guidanceActive=YES;}// Listener for route change events.-(void)navigatorDidChangeRoute:(GMSNavigator*)navigator{NSLog(@"The route has changed.");}// Listener for time to next destination.-(void)navigator:(GMSNavigator*)navigatordidUpdateRemainingTime:(NSTimeInterval)time{NSLog(@"Time to next destination: %f",time);}// Listener for distance to next destination.-(void)navigator:(GMSNavigator*)navigatordidUpdateRemainingDistance:(CLLocationDistance)distance{doublemiles=distance*0.00062137;NSLog(@"%@",[NSStringstringWithFormat:@"Distance to next destination: %.2f.",miles]);}// Listener for traffic updates for next destination-(void)navigator:(GMSNavigator*)navigatordidUpdateDelayCategory:(GMSNavigationDelayCategory)delayCategory{NSLog(@"Delay category to next destination: %ld.",delayCategory);}// Listener for suggested lighting mode changes.-(void)navigator:(GMSNavigator*)navigatordidChangeSuggestedLightingMode:(GMSNavigationLightingMode)lightingMode{NSLog(@"Suggested lighting mode has changed: %ld",(long)lightingMode);// Change to the suggested lighting mode._mapView.lightingMode=lightingMode;}#pragma mark - Programmatic UI elements// Add a button to the view.-(void)makeButton{// Start navigation.UIButton*navButton=[UIButtonbuttonWithType:UIButtonTypeCustom];[navButtonaddTarget:selfaction:@selector(startNav)forControlEvents:UIControlEventTouchUpInside];[navButtonsetTitle:@"Navigate"forState:UIControlStateNormal];[navButtonsetBackgroundColor:[UIColorblueColor]];[navButtonsetAlpha:0.5];navButton.frame=CGRectMake(5.0,150.0,100.0,35.0);[_mapViewaddSubview:navButton];}@end
Declaração de conformidade com os protocolos necessários
Antes de implementar os métodos de navegação, o controlador de visualização precisa adotar os
protocolos:
Depois de adotar os protocolos de navegação, defina os listeners para o controlador de visualização. Por exemplo, adicione o código a seguir ao método viewDidLoad().
Receber ou interromper atualizações de localização
As atualizações de localização são necessárias para mostrar o progresso do usuário no mapa.
A instância location expõe as seguintes propriedades:
Propriedade de local
Descrição
altitude
Altitude atual.
coordinate.latitude
Coordenada de latitude ajustada à via atual.
coordinate.longitude
Coordenada de longitude ajustada à via atual.
curso
Inclinação atual em graus.
velocidade
Velocidade atual.
timestamp
Data/hora da leitura atual.
.
Para receber atualizações contínuas de localização, chame
mapView.roadSnappedLocationProvider.startUpdatingLocation e use o
GMSRoadSnappedLocationProviderListener para processar o evento didUpdateLocation.
O exemplo a seguir mostra como chamar startUpdatingLocation:
O app usa o evento didArriveAtWaypoint para detectar quando um destino foi
alcançado. Você pode retomar a orientação e avançar para o próximo ponto de referência
chamando continueToNextDestination() e reativando a orientação. O app
precisa reativar a orientação depois de chamar continueToNextDestination().
Depois que o app chama continueToNextDestination, o navegador não tem mais
dados sobre o destino anterior. Se você quiser analisar informações sobre um trecho de
rota, recupere isso do navegador antes de chamar
continueToNextDestination().
O exemplo de código a seguir mostra um método para processar o evento didArriveAtWaypoint:
Swift
funcnavigator(_navigator:GMSNavigator,didArriveAtwaypoint:GMSNavigationWaypoint){print("You have arrived at: \(waypoint.title)")mapView.navigator?.continueToNextDestination()mapView.navigator?.isGuidanceActive=true}
Para receber uma notificação sempre que a rota for alterada, crie um método para
processar o evento navigatorDidChangeRoute. Você pode acessar a nova rota usando as propriedades routeLegs e currentRouteLeg de GMSNavigator.
Para receber atualizações contínuas do tempo até o destino, crie um método para processar o evento
didUpdateRemainingTime. O parâmetro time fornece o tempo estimado, em segundos, até o próximo destino.
Swift
funcnavigator(_navigator:GMSNavigator,didUpdateRemainingTimetime:TimeInterval){print("Time to next destination: \(time)")}
Objective-C
-(void)navigator:(GMSNavigator*)navigatordidUpdateRemainingTime:(NSTimeInterval)time{NSLog(@"Time to nextdestination:%f", time); }
Para definir a mudança mínima no tempo estimado até o próximo destino, defina a propriedade timeUpdateThreshold em GMSNavigator. O valor é especificado em segundos. Se essa propriedade não for definida, os serviços usarão um valor padrão de um segundo.
Swift
navigator?.timeUpdateThreshold=10
Objective-C
navigator.timeUpdateThreshold=10;
Receber atualizações sobre a distância até o destino
Para receber atualizações contínuas da distância até o destino, crie um método para processar
o evento didUpdateRemainingDistance. O parâmetro distance fornece a distância estimada, em metros, até o próximo destino.
Swift
funcnavigator(_navigator:GMSNavigator,didUpdateRemainingDistancedistance:CLLocationDistance){letmiles=distance*0.00062137print("Distance to nextdestination: \(miles) miles.")}
Para definir a mudança mínima na distância estimada até o próximo destino, defina a propriedade
distanceUpdateThreshold em GMSNavigator (o valor é especificado em
metros). Se essa propriedade não for definida, os serviços usarão um valor padrão de um metro.
Swift
navigator?.distanceUpdateThreshold=100
Objective-C
navigator.distanceUpdateThreshold=100;
Como receber atualizações de trânsito
Para receber atualizações contínuas do fluxo de tráfego para o restante do trajeto, crie um método para processar o evento didUpdateDelayCategory. Uma chamada para delayCategoryToNextDestination retorna GMSNavigationDelayCategory, que fornece um valor de 0 a 3. As atualizações da categoria são baseadas na posição atual do usuário do app. Se os dados de tráfego não estiverem disponíveis, GMSNavigationDelayCategory vai retornar 0. Os números, de 1 a 3, indicam um fluxo crescente de leve a intenso.
Swift
funcnavigator(_navigator:GMSNavigator,didUpdatedelayCategory:GMSNavigationDelayCategory){print("Traffic flow to next destination:\(delayCategory)")}
Objective-C
-(void)navigator:(GMSNavigator*)navigatordidUpdateDelayCategory:(GMSNavigationDelayCategory)delayCategory{NSLog(@"Traffic flow to next destination: %ld",(long)delayCategory);}
A propriedade GMSNavigationDelayCategory expõe os seguintes níveis de atraso:
Categoria de atraso
Descrição
GMSNavigationDelayCategoryNoData
0: indisponível, sem dados de trânsito ou
a rota.
GMSNavigationDelayCategoryHeavy
1 - Forte.
GMSNavigationDelayCategoryMedium
2 - Médio.
GMSNavigationDelayCategoryLight
3 – Leve.
Receber atualizações de velocidade
Para receber atualizações quando um motorista exceder o limite de velocidade, crie um método
para processar o evento didUpdateSpeedingPercentage.
Swift
// Listener to handle speeding events. func navigator( _ navigator:GMSNavigator,didUpdateSpeedingPercentagepercentageAboveLimit:CGFloat){print("Speed is \(percentageAboveLimit) above the limit.")}
Objective-C
// Listener to handle speeding events. - (void)navigator:(GMSNavigator*)navigatordidUpdateSpeedingPercentage:(CGFloat)percentageAboveLimit{NSLog(@"Speed is %f percent above the limit.",percentageAboveLimit);}
Mudar o modo de iluminação sugerido
Para receber atualizações sobre mudanças estimadas na iluminação, crie um método para processar
o evento didChangeSuggestedLightingMode.
Swift
// Define a listener for suggested changes to lighting mode. func navigator(_navigator:GMSNavigator,didChangeSuggestedLightingModelightingMode:GMSNavigationLightingMode){print("Suggested lighting mode has changed:\(String(describing:lightingMode))")// Make the suggested change. mapView.lightingMode = lightingMode }
Objective-C
// Define a listener for suggested changes to lighting mode.-(void)navigator:(GMSNavigator*)navigatordidChangeSuggestedLightingMode:(GMSNavigationLightingMode)lightingMode{NSLog(@"Suggested lighting mode haschanged:%ld", (long)lightingMode);// Make the suggested change. _mapView.lightingMode = lightingMode; }
[null,null,["Última atualização 2025-08-31 UTC."],[[["\u003cp\u003eThe Navigation SDK for iOS allows you to respond to real-time navigation events like route changes, arrival, and location updates using listeners.\u003c/p\u003e\n"],["\u003cp\u003e\u003ccode\u003eGMSRoadSnappedLocationProviderListener\u003c/code\u003e and \u003ccode\u003eGMSNavigatorListener\u003c/code\u003e protocols handle events like location updates, speeding, and destination arrival.\u003c/p\u003e\n"],["\u003cp\u003eLocation updates can be managed for real-time tracking and background operation, impacting battery life.\u003c/p\u003e\n"],["\u003cp\u003eThe \u003ccode\u003eGMSNavigator\u003c/code\u003e provides methods to track and respond to waypoint arrivals, route changes, time and distance to destination, traffic flow, speeding percentage, and suggested lighting mode.\u003c/p\u003e\n"],["\u003cp\u003e\u003ccode\u003eGMSNavigatorDelegate\u003c/code\u003e and \u003ccode\u003eGMSRoadSnappedLocationProviderDelegate\u003c/code\u003e are deprecated and replaced by \u003ccode\u003eGMSRoadSnappedLocationProviderListener\u003c/code\u003e and \u003ccode\u003eGMSNavigatorListener\u003c/code\u003e.\u003c/p\u003e\n"]]],[],null,[]]