Часто задаваемые вопросы

Подробная информация о товаре

Проблемы

Сеть

Данные

Настройка пользовательского интерфейса

Маршрутизация

Симулятор

Рабочие процессы

Услуги мобильности

Подробная информация о товаре

Ваше приложение должно содержать диалоговое окно с уведомлением об условиях использования Navigation SDK, которое каждый водитель должен принять. Это диалоговое окно предоставляет водителю возможность согласиться с условиями использования. Текстовый файл с условиями предоставляется вместе с Navigation SDK.
В Android для отображения диалогового окна с условиями используйте метод NavigationApi.showTermsAndConditionsDialog .
В iOS вызовите GMSNavigationServices.showTermsAndConditionsDialogIfNeededWithCompanyName .
Все языки, поддерживаемые Google Maps Mobile, автоматически доступны для Navigation SDK. На устройстве установлен системный язык по умолчанию, и приложение не может изменить эту настройку; однако приложение имеет доступ к более чем 70 языкам.

Да. В Android после запуска LocationListener продолжает работать в фоновом режиме. Ваше приложение продолжает привязывать местоположение и поддерживать азимут.

В iOS для продолжения получения обновлений местоположения (позиционирования и азимута) в фоновом режиме необходимо реализовать привязку к дороге и установить allowsBackgroundLocationUpdates в YES .

Да. При создании или изменении маршрута RouteChangeListener предоставляет полилинии.

Нет, для работы Navigation SDK не требуется установленное на устройстве приложение Google Maps Mobile.
Нет, в настоящее время SDK для навигации не предоставляет эту функциональность.
Да. Информация о направлении движения доступна и отображается по умолчанию.

Проблемы

В Xcode 12 приложения некорректно компилируются для симулятора. Как это исправить?

Чтобы исправить эту проблему, откройте настройки сборки вашего проекта Xcode и добавьте arm64 в список Excluded Architectures только для сборок "симулятора iOS".

Для получения более подробной информации см. следующую ветку обсуждения на StackOverflow .

GMSMapView не загружается.

Если GMSMapView не загружается:

  • Убедитесь, что NavSDK включен в Cloud Console.
  • Если Nav SDK установлен, но ваш проект не использует API Nav SDK, удалите его из исполняемого файла.

Сеть

Как SDK навигации обрабатывает плохое соединение?
Навигационный SDK предварительно загружает маршрут для каждой поездки. Предварительно загруженная информация включает данные о маршруте на 15-20 минут, а также альтернативные маршруты на случай, если водитель отклонится от основного маршрута. Навигационный SDK определяет приблизительное местоположение, используя GPS-приемник и датчики устройства.
Доступен ли автономный режим?
Нет, в настоящее время SDK для навигации не предлагает автономный режим; однако SDK предоставляет предварительно кэшированную информацию о маршруте.

Данные

Могу ли я получить список всех остановок/пунктов назначения в маршруте до его начала?

Да. В Android для получения маршрута необходимо вызвать метод Navigator.getRouteSegments() .

В iOS вызовите GMSNavigator.routeLegs(read) .

Доступна ли пошаговая инструкция по прокладке маршрута в начале пути?
Да. SDK навигации предоставляет список сегментов маршрута. Кроме того, водитель может пролистывать карточку с указаниями в заголовке, чтобы увидеть каждый маневр.
Как информация о предполагаемом времени прибытия (ETA) доводится до пользователей приложения?

В Android для предоставления пользователям приложения информации о предполагаемом времени прибытия выполните следующие действия:

  1. Получите время и расстояние для всех путевых точек, используя Navigator.getTimeAndDistanceList() .
  2. Передайте эту информацию в клиентское приложение так же, как и информацию о предполагаемом времени прибытия водителя.

В iOS выполните следующие действия, чтобы предоставить пользователям приложения информацию о предполагаемом времени прибытия:

  1. Получите сегменты маршрута, используя Navigator.getRouteSegments() .
  2. Вызывайте метод GMSNavigator.timeToNextDestination для каждого участка пути.
  3. Передайте информацию о времени в клиентское приложение так же, как и информацию о расчетном времени прибытия водителя.
Можно ли использовать RoadSnappedLocationProvider для получения текущего местоположения водителя на снимке, если навигация не находится в фоновом режиме?

Да. В Android компонент RoadSnappedLocationProvider по умолчанию работает в фоновом режиме.

В iOS для поддержания работы навигации в фоновом режиме необходимо реализовать обработчик событий для GMSRoadSnappedLocationProviderListener и установить свойство allowsBackgroundLocationUpdates в TRUE .

Поддерживает ли SDK для навигации геозонирование?

Нет. В контексте навигации, remainingTimeOrdistanceChangeListener имеет преимущество перед геозоной. Геозона может не учитывать геометрию дороги и может быть не центрирована точно на той точке, к которой направляется водитель.

Эту функциональность можно приблизительно воспроизвести с помощью remainingTimeOrdistanceChangeListener .

  1. Установите пороговое значение, чтобы определить частоту обратных вызовов.
  2. Проверьте оставшееся расстояние до пункта назначения.

Например, если вы установите пороговое значение в 100 м, вы получите обратный вызов, когда расстояние до пункта назначения изменится на 100 м. По мере уменьшения расстояния вы можете изменить это пороговое значение на меньшее и получать обратные вызовы чаще. Затем проверьте оставшееся расстояние, чтобы определить, достаточно ли вы близки к месту посадки/высадки.

В iOS реализуйте обработчик событий GMSNavigatorListener.didUpdateRemainingDistance для управления расстоянием между уведомлениями.

Можно ли отключить уведомления, когда приложение «Навигация» работает в фоновом режиме?

Да. В Android для управления уведомлениями используйте Navigator.setHeadsUpNotificationEnabled . Этот метод имеет логический аргумент. FALSE отключает уведомления; TRUE включает уведомления.

В iOS фоновые уведомления для местоположений, зафиксированных на дороге, можно отключить, установив параметр GMSRoadSnappedLocationProvider.allowsBackgroundLocationUpdates в значение NO.

Чтобы отключить фоновую обработку для других уведомлений о местоположении, вызовите GMSNavigator.sendsBackgroundNotifications(NO) .

Настройка пользовательского интерфейса

Можно ли выделить цветом оптимальный вариант маршрута?
Нет. Цветовое кодирование конкретного варианта маршрута в настоящее время не поддерживается.
Может ли навигационный SDK отображать расчетное время прибытия в конечный пункт назначения?

Да. В Android используйте следующие методы:

  1. Получите время и расстояние для всех путевых точек, используя Navigator.getTimeAndDistanceList() .
  2. Скройте расчетное время прибытия текущей точки маршрута, используя NavigationFragment.setEtaCardEnabled(false) .
  3. Отобразить расчетное время прибытия в конечный пункт назначения.

В iOS используйте следующее:

  1. Вызовите GMSNavigator.routeLegs(read) .
  2. На последнем отрезке пути позвоните по номеру GMSNavigator.timeToNextDestination .
  3. Скройте расчетное время прибытия текущей точки маршрута, заменив значение MSMapView.settings.navigationFooterEnabled=NO на FALSE.
  4. Отобразить расчетное время прибытия в конечный пункт назначения.
Как скрыть информацию о предполагаемом времени прибытия?

Отключить карты ETA можно следующими способами:

  • В Android используйте navigationView.setEtaCardEnabled(false) .
  • В iOS используйте GMSMapView.settings.navigationFooterEnabled=NO .
Какие параметры настройки пользовательского интерфейса доступны для карточек в заголовке и нижнем колонтитуле?

В Android для установки цвета фона используется StylingOptions . Чтобы скрыть или показать заголовок и нижний колонтитул, используйте функции-члены setHeaderEnabled и setFooterEnabled класса NavigationFragment .

В iOS для установки цвета фона используйте GMSMapView.settings.navigationHeaderPrimaryBackgroundColor . Чтобы скрыть или показать заголовок и нижний колонтитул, используйте свойства navigationFooterEnabled и navigationHeaderEnabled класса GMSUISettings .

Маршрутизация

Могу ли я указать водителю конкретный маршрут или удалить альтернативные маршруты?
Нет. По умолчанию предоставляется несколько маршрутов, и самый быстрый маршрут имеет приоритет. Вы можете повлиять на маршрут по умолчанию, добавив в свой запрос параметры, например, «избегать автомагистралей и платных дорог». Добавление путевых точек также влияет на маршрут.
Могу ли я отображать пользователю приложения другую метку для пункта назначения, отличную от стандартного местоположения?

Да. В Android создайте Marker с пользовательским заголовком для пункта назначения и координатами широты/долготы. SDK навигации отобразит пользовательский заголовок и координаты на NavigationMap .

В iOS вы создаете и отображаете объект GMSMarker для целевого объекта.

Можно ли использовать Navigation SDK для отслеживания отклонений от заданного маршрута?

Да. В Android используйте Navigator.setRouteChangedListener , чтобы получать уведомления об изменении маршрута или рекомендации нового маршрута:

  1. Зарегистрируйте слушатель, который проверяет положение устройства вдоль маршрута с помощью метода Navigator.setRouteChangedListener .
  2. Добавьте код в обработчик события обратного вызова onRouteChanged :
    • Отправьте пользователю приложения сообщение с обновленной информацией о предполагаемом времени прибытия и расстоянии.
    • Отслеживайте местоположение устройства.
    • [необязательно] Добавьте другие функции, необходимые вашему приложению для обработки ситуаций, когда водитель отклоняется от заданного маршрута.

В iOS используйте GMSNavigator и его обработчики событий, чтобы получать уведомления об изменении маршрута или о предложении нового маршрута:

  1. В контроллере представления карты реализуйте протоколы GMSNavigatorListener и GMSRoadSnappedLocationProviderListener .
  2. Реализуйте метод GMSNavigatorListener.navigatorDidChangeRoute .
  3. Для доступа к новому маршруту используйте свойства routeLegs и currentRouteLeg объекта GMSNavigator .
Может ли водитель выйти из навигации, не завершив маршрут?

Да. В Android для остановки навигации вызовите метод Navigator.stopGuidance() .

В iOS вызовите GMSNavigator.clearDestinations .

Симулятор

Поддерживает ли симулятор изменение маршрута?

Да. В Android вызовите метод simulateLocationsAlongNewRoute , чтобы смоделировать поездку, включающую изменение маршрута. Метод simulateLocationsAlongExistingRoute игнорирует изменения существующего маршрута.

В iOS для имитации поездки с изменением маршрута используйте GMSLocationSimulator.simulateAlongNewRouteToDestinations . Если изменений маршрута не ожидается, можно использовать GMSLocationSimulator.simulateLocationsAlongExistingRoute или GMSLocationSimulator.simulateAlongNewRouteToDestinations .

Рабочие процессы

Как закрыть уведомление после закрытия активности, содержащей фрагмент навигации?

Уведомление о навигации остается видимым во время навигации, даже когда действие завершено. Когда транспортное средство прибывает в пункт назначения, навигация останавливается, и уведомление исчезает.

Для обработки кликов по уведомлению используйте Navigator.startGuidance(intent resumeIntent) . resume intent срабатывает, когда пользователь приложения кликает по уведомлению. Как правило, Navigator.startguidance(getIntent()) вызывается из главного Activity, которое повторно вызывает Activity, когда пользователь приложения кликает по уведомлению.

Услуги мобильности

Чем отличается использование Navigation SDK для клиентов, пользующихся услугами мобильной связи?

Сервисы Google Maps Platform Mobility Services предлагают набор API и SDK для поддержки корпоративных потребностей транспортных и логистических компаний. Для клиентов Mobility Services SDK навигации обычно используется в сочетании с другими сервисами для оптимизации маршрутов, диспетчеризации, отслеживания задач, анализа автопарка и многого другого. Стоимость SDK навигации также отличается для клиентов Mobility Services. Для получения дополнительной информации см. документацию Mobility Services .

Средства передвижения доступны только избранным клиентам. Для получения дополнительной информации свяжитесь со своим торговым представителем.

Как я могу узнать, являюсь ли я клиентом службы мобильной связи?
Если вы не уверены, используете ли вы Navigation SDK как клиент Mobility Services, найдите вызов метода ReportBillableEvent в своем коде. Вызывать метод ReportBillableEvent должны только клиенты Mobility Services.

Как осуществляется оплата SDK навигации для клиентов мобильных сервисов?
Для клиентов, использующих сервисы мобильной связи, выставление счетов и ценообразование для навигационного SDK зависят от вашего соглашения об оказании услуг с платформой Google Maps. Информацию о проверке корректности выставления счетов за использование сервисов мобильной связи см. в разделе «Проверка выставления счетов» . Для получения дополнительной информации о выставлении счетов за сервисы мобильной связи обратитесь к своему торговому представителю.

Какие API навигационного SDK следует использовать только клиентам мобильных сервисов?

В SDK навигации есть несколько API, предназначенных только для использования клиентами Mobility Services , которым Google выставляет счета за каждую транзакцию. Если вы не являетесь клиентом Mobility Services, следующие методы не выполняют никаких действий:

Если я являюсь клиентом Mobility Services, могу ли я также использовать реализацию Navigation SDK, не относящуюся к Mobility Services?

Да, клиенты Mobility Services могут использовать как реализации Navigation SDK, относящиеся к Mobility Services, так и реализации, не относящиеся к Mobility Services. Однако в приложении одновременно можно использовать только один тип реализации. Также необходимо создать новый проект Google Cloud, учетную запись для выставления счетов и ключ API, отличные от тех, которые вы используете с реализацией Mobility Services. Для получения дополнительной информации см. обзор настройки Navigation SDK .

Для получения дополнительной информации об использовании реализации Navigation SDK, не относящейся к сервисам мобильной связи, включая миграцию приложения с одного типа реализации на другой, обратитесь к представителю вашей учетной записи Google.

Примечание: Если вы не являетесь клиентом Mobility Services и хотите узнать больше о наборе API и SDK Mobility Services, свяжитесь со службой продаж Google Maps Platform .

,

Часто задаваемые вопросы

Подробная информация о товаре

Проблемы

Сеть

Данные

Настройка пользовательского интерфейса

Маршрутизация

Симулятор

Рабочие процессы

Услуги мобильности

Подробная информация о товаре

Ваше приложение должно содержать диалоговое окно с уведомлением об условиях использования Navigation SDK, которое каждый водитель должен принять. Это диалоговое окно предоставляет водителю возможность согласиться с условиями использования. Текстовый файл с условиями предоставляется вместе с Navigation SDK.
В Android для отображения диалогового окна с условиями используйте метод NavigationApi.showTermsAndConditionsDialog .
В iOS вызовите GMSNavigationServices.showTermsAndConditionsDialogIfNeededWithCompanyName .
Все языки, поддерживаемые Google Maps Mobile, автоматически доступны для Navigation SDK. На устройстве установлен системный язык по умолчанию, и приложение не может изменить эту настройку; однако приложение имеет доступ к более чем 70 языкам.

Да. В Android после запуска LocationListener продолжает работать в фоновом режиме. Ваше приложение продолжает привязывать местоположение и поддерживать азимут.

В iOS для продолжения получения обновлений местоположения (позиционирования и азимута) в фоновом режиме необходимо реализовать привязку к дороге и установить allowsBackgroundLocationUpdates в YES .

Да. При создании или изменении маршрута RouteChangeListener предоставляет полилинии.

Нет, для работы Navigation SDK не требуется установленное на устройстве приложение Google Maps Mobile.
Нет, в настоящее время SDK для навигации не предоставляет эту функциональность.
Да. Информация о направлении движения доступна и отображается по умолчанию.

Проблемы

В Xcode 12 приложения некорректно компилируются для симулятора. Как это исправить?

Чтобы исправить эту проблему, откройте настройки сборки вашего проекта Xcode и добавьте arm64 в список Excluded Architectures только для сборок "симулятора iOS".

Для получения более подробной информации см. следующую ветку обсуждения на StackOverflow .

GMSMapView не загружается.

Если GMSMapView не загружается:

  • Убедитесь, что NavSDK включен в Cloud Console.
  • Если Nav SDK установлен, но ваш проект не использует API Nav SDK, удалите его из исполняемого файла.

Сеть

Как SDK навигации обрабатывает плохое соединение?
Навигационный SDK предварительно загружает маршрут для каждой поездки. Предварительно загруженная информация включает данные о маршруте на 15-20 минут, а также альтернативные маршруты на случай, если водитель отклонится от основного маршрута. Навигационный SDK определяет приблизительное местоположение, используя GPS-приемник и датчики устройства.
Доступен ли автономный режим?
Нет, в настоящее время SDK для навигации не предлагает автономный режим; однако SDK предоставляет предварительно кэшированную информацию о маршруте.

Данные

Могу ли я получить список всех остановок/пунктов назначения в маршруте до его начала?

Да. В Android для получения маршрута необходимо вызвать метод Navigator.getRouteSegments() .

В iOS вызовите GMSNavigator.routeLegs(read) .

Доступна ли пошаговая инструкция по прокладке маршрута в начале пути?
Да. SDK навигации предоставляет список сегментов маршрута. Кроме того, водитель может пролистывать карточку с указаниями в заголовке, чтобы увидеть каждый маневр.
Как информация о предполагаемом времени прибытия (ETA) доводится до пользователей приложения?

В Android для предоставления пользователям приложения информации о предполагаемом времени прибытия выполните следующие действия:

  1. Получите время и расстояние для всех путевых точек, используя Navigator.getTimeAndDistanceList() .
  2. Передайте эту информацию в клиентское приложение так же, как и информацию о предполагаемом времени прибытия водителя.

В iOS выполните следующие действия, чтобы предоставить пользователям приложения информацию о предполагаемом времени прибытия:

  1. Получите сегменты маршрута, используя Navigator.getRouteSegments() .
  2. Вызывайте метод GMSNavigator.timeToNextDestination для каждого участка пути.
  3. Передайте информацию о времени в клиентское приложение так же, как и информацию о расчетном времени прибытия водителя.
Можно ли использовать RoadSnappedLocationProvider для получения текущего местоположения водителя на снимке, если навигация не находится в фоновом режиме?

Да. В Android компонент RoadSnappedLocationProvider по умолчанию работает в фоновом режиме.

В iOS для поддержания работы навигации в фоновом режиме необходимо реализовать обработчик событий для GMSRoadSnappedLocationProviderListener и установить свойство allowsBackgroundLocationUpdates в TRUE .

Поддерживает ли SDK для навигации геозонирование?

Нет. В контексте навигации, remainingTimeOrdistanceChangeListener имеет преимущество перед геозоной. Геозона может не учитывать геометрию дороги и может быть не центрирована точно на той точке, к которой направляется водитель.

Эту функциональность можно приблизительно воспроизвести с помощью remainingTimeOrdistanceChangeListener .

  1. Установите пороговое значение, чтобы определить частоту обратных вызовов.
  2. Проверьте оставшееся расстояние до пункта назначения.

Например, если вы установите пороговое значение в 100 м, вы получите обратный вызов, когда расстояние до пункта назначения изменится на 100 м. По мере уменьшения расстояния вы можете изменить это пороговое значение на меньшее и получать обратные вызовы чаще. Затем проверьте оставшееся расстояние, чтобы определить, достаточно ли вы близки к месту посадки/высадки.

В iOS реализуйте обработчик событий GMSNavigatorListener.didUpdateRemainingDistance для управления расстоянием между уведомлениями.

Можно ли отключить уведомления, когда приложение «Навигация» работает в фоновом режиме?

Да. В Android для управления уведомлениями используйте Navigator.setHeadsUpNotificationEnabled . Этот метод имеет логический аргумент. FALSE отключает уведомления; TRUE включает уведомления.

В iOS фоновые уведомления для местоположений, зафиксированных на дороге, можно отключить, установив параметр GMSRoadSnappedLocationProvider.allowsBackgroundLocationUpdates в значение NO.

Чтобы отключить фоновую обработку для других уведомлений о местоположении, вызовите GMSNavigator.sendsBackgroundNotifications(NO) .

Настройка пользовательского интерфейса

Можно ли выделить цветом оптимальный вариант маршрута?
Нет. Цветовое кодирование конкретного варианта маршрута в настоящее время не поддерживается.
Может ли навигационный SDK отображать расчетное время прибытия в конечный пункт назначения?

Да. В Android используйте следующие методы:

  1. Получите время и расстояние для всех путевых точек, используя Navigator.getTimeAndDistanceList() .
  2. Скройте расчетное время прибытия текущей точки маршрута, используя NavigationFragment.setEtaCardEnabled(false) .
  3. Отобразить расчетное время прибытия в конечный пункт назначения.

В iOS используйте следующее:

  1. Вызовите GMSNavigator.routeLegs(read) .
  2. На последнем отрезке пути позвоните по номеру GMSNavigator.timeToNextDestination .
  3. Скройте расчетное время прибытия текущей точки маршрута, заменив значение MSMapView.settings.navigationFooterEnabled=NO на FALSE.
  4. Отобразить расчетное время прибытия в конечный пункт назначения.
Как скрыть информацию о предполагаемом времени прибытия?

Отключить карты ETA можно следующими способами:

  • В Android используйте navigationView.setEtaCardEnabled(false) .
  • В iOS используйте GMSMapView.settings.navigationFooterEnabled=NO .
Какие параметры настройки пользовательского интерфейса доступны для карточек в заголовке и нижнем колонтитуле?

В Android для установки цвета фона используется StylingOptions . Чтобы скрыть или показать заголовок и нижний колонтитул, используйте функции-члены setHeaderEnabled и setFooterEnabled класса NavigationFragment .

В iOS для установки цвета фона используйте GMSMapView.settings.navigationHeaderPrimaryBackgroundColor . Чтобы скрыть или показать заголовок и нижний колонтитул, используйте свойства navigationFooterEnabled и navigationHeaderEnabled класса GMSUISettings .

Маршрутизация

Могу ли я указать водителю конкретный маршрут или удалить альтернативные маршруты?
Нет. По умолчанию предоставляется несколько маршрутов, и самый быстрый маршрут имеет приоритет. Вы можете повлиять на маршрут по умолчанию, добавив в свой запрос параметры, например, «избегать автомагистралей и платных дорог». Добавление путевых точек также влияет на маршрут.
Могу ли я отображать пользователю приложения другую метку для пункта назначения, отличную от стандартного местоположения?

Да. В Android создайте Marker с пользовательским заголовком для пункта назначения и координатами широты/долготы. SDK навигации отобразит пользовательский заголовок и координаты на NavigationMap .

В iOS вы создаете и отображаете объект GMSMarker для целевого объекта.

Можно ли использовать Navigation SDK для отслеживания отклонений от заданного маршрута?

Да. В Android используйте Navigator.setRouteChangedListener , чтобы получать уведомления об изменении маршрута или рекомендации нового маршрута:

  1. Зарегистрируйте слушатель, который проверяет положение устройства вдоль маршрута с помощью метода Navigator.setRouteChangedListener .
  2. Добавьте код в обработчик события обратного вызова onRouteChanged :
    • Отправьте пользователю приложения сообщение с обновленной информацией о предполагаемом времени прибытия и расстоянии.
    • Отслеживайте местоположение устройства.
    • [необязательно] Добавьте другие функции, необходимые вашему приложению для обработки ситуаций, когда водитель отклоняется от заданного маршрута.

В iOS используйте GMSNavigator и его обработчики событий, чтобы получать уведомления об изменении маршрута или о предложении нового маршрута:

  1. В контроллере представления карты реализуйте протоколы GMSNavigatorListener и GMSRoadSnappedLocationProviderListener .
  2. Реализуйте метод GMSNavigatorListener.navigatorDidChangeRoute .
  3. Для доступа к новому маршруту используйте свойства routeLegs и currentRouteLeg объекта GMSNavigator .
Может ли водитель выйти из навигации, не завершив маршрут?

Да. В Android для остановки навигации вызовите метод Navigator.stopGuidance() .

В iOS вызовите GMSNavigator.clearDestinations .

Симулятор

Поддерживает ли симулятор изменение маршрута?

Да. В Android вызовите метод simulateLocationsAlongNewRoute , чтобы смоделировать поездку, включающую изменение маршрута. Метод simulateLocationsAlongExistingRoute игнорирует изменения существующего маршрута.

В iOS для имитации поездки с изменением маршрута используйте GMSLocationSimulator.simulateAlongNewRouteToDestinations . Если изменений маршрута не ожидается, можно использовать GMSLocationSimulator.simulateLocationsAlongExistingRoute или GMSLocationSimulator.simulateAlongNewRouteToDestinations .

Рабочие процессы

Как закрыть уведомление после закрытия активности, содержащей фрагмент навигации?

Уведомление о навигации остается видимым во время навигации, даже когда действие завершено. Когда транспортное средство прибывает в пункт назначения, навигация останавливается, и уведомление исчезает.

Для обработки кликов по уведомлению используйте Navigator.startGuidance(intent resumeIntent) . resume intent срабатывает, когда пользователь приложения кликает по уведомлению. Как правило, Navigator.startguidance(getIntent()) вызывается из главного Activity, которое повторно вызывает Activity, когда пользователь приложения кликает по уведомлению.

Услуги мобильности

Чем отличается использование Navigation SDK для клиентов, пользующихся услугами мобильной связи?

Сервисы Google Maps Platform Mobility Services предлагают набор API и SDK для поддержки корпоративных потребностей транспортных и логистических компаний. Для клиентов Mobility Services SDK навигации обычно используется в сочетании с другими сервисами для оптимизации маршрутов, диспетчеризации, отслеживания задач, анализа автопарка и многого другого. Стоимость SDK навигации также отличается для клиентов Mobility Services. Для получения дополнительной информации см. документацию Mobility Services .

Средства передвижения доступны только избранным клиентам. Для получения дополнительной информации свяжитесь со своим торговым представителем.

Как я могу узнать, являюсь ли я клиентом службы мобильной связи?
Если вы не уверены, используете ли вы Navigation SDK как клиент Mobility Services, найдите вызов метода ReportBillableEvent в своем коде. Вызывать метод ReportBillableEvent должны только клиенты Mobility Services.

Как осуществляется оплата SDK навигации для клиентов мобильных сервисов?
Для клиентов, использующих сервисы мобильной связи, выставление счетов и ценообразование для навигационного SDK зависят от вашего соглашения об оказании услуг с платформой Google Maps. Информацию о проверке корректности выставления счетов за использование сервисов мобильной связи см. в разделе «Проверка выставления счетов» . Для получения дополнительной информации о выставлении счетов за сервисы мобильной связи обратитесь к своему торговому представителю.

Какие API навигационного SDK следует использовать только клиентам мобильных сервисов?

В SDK навигации есть несколько API, предназначенных только для использования клиентами Mobility Services , которым Google выставляет счета за каждую транзакцию. Если вы не являетесь клиентом Mobility Services, следующие методы не выполняют никаких действий:

Если я являюсь клиентом Mobility Services, могу ли я также использовать реализацию Navigation SDK, не относящуюся к Mobility Services?

Да, клиенты Mobility Services могут использовать как реализации Navigation SDK, относящиеся к Mobility Services, так и реализации, не относящиеся к Mobility Services. Однако в приложении одновременно можно использовать только один тип реализации. Также необходимо создать новый проект Google Cloud, учетную запись для выставления счетов и ключ API, отличные от тех, которые вы используете с реализацией Mobility Services. Для получения дополнительной информации см. обзор настройки Navigation SDK .

Для получения дополнительной информации об использовании реализации Navigation SDK, не относящейся к сервисам мобильной связи, включая миграцию приложения с одного типа реализации на другой, обратитесь к представителю вашей учетной записи Google.

Примечание: Если вы не являетесь клиентом Mobility Services и хотите узнать больше о наборе API и SDK Mobility Services, свяжитесь со службой продаж Google Maps Platform .

,

Часто задаваемые вопросы

Подробная информация о товаре

Проблемы

Сеть

Данные

Настройка пользовательского интерфейса

Маршрутизация

Симулятор

Рабочие процессы

Услуги мобильности

Подробная информация о товаре

Your app must implement a dialog with the Navigation SDK Terms of Service notice that each driver must accept. This dialog gives the driver the opportunity to agree with the Terms of Service. A text file of the terms is provided with the Navigation SDK.
In Android, use the NavigationApi.showTermsAndConditionsDialog method to display the dialog containing the terms.
In iOS, call GMSNavigationServices.showTermsAndConditionsDialogIfNeededWithCompanyName .
Any languages supported by Google Maps Mobile are automatically available for the Navigation SDK. A device has a default system language and an app cannot change that setting; however, the app has access to over 70 languages.

Yes. In Android, once started, the LocationListener continues to run in the background. Your app continues road snapping the position and maintains the bearing.

In iOS, to continue receiving location updates of position and bearing in the background, implement road snapping and set allowsBackgroundLocationUpdates to YES .

Yes. When a route is created or changed, the RouteChangeListener provides polylines.

No, the Navigation SDK does not require Google Maps Mobile to be installed on the device.
No, the Navigation SDK does not provide this functionality at this time.
Yes. The traffic direction is available and displayed by default.

Проблемы

In Xcode 12, apps don't build correctly for the simulator. How can I fix this?

To fix this issue, open your Xcode project Build Settings, and add arm64 to the Excluded Architectures for "iOS Simulator" builds only.

For more information, see the following StackOverflow thread .

GMSMapView does not load.

If the GMSMapView does not load:

  • Check that NavSDK is enabled in Cloud Console.
  • If the Nav SDK is installed, but your project does not use Nav SDK APIs, remove it from your binary.

Сеть

How does the Navigation SDK handle poor connectivity?
The Navigation SDK pre-caches the route for each journey. The pre-cached information includes routing information for 15-20 minutes, and route alternatives in case the driver deviates from the route. The Navigation SDK approximates position using the device GPS and sensors.
Is an offline mode available?
No, the Navigation SDK does not offer an offline mode at this time; however, the SDK does provide pre-cached information for a journey.

Данные

Can I retrieve all of the stops/destinations in a journey before starting the route?

Yes. In Android, to retrieve the directions for a route, call Navigator.getRouteSegments() .

In iOS, call GMSNavigator.routeLegs(read) .

Is turn-by-turn route guidance available at the start of a route?
Yes. The Navigation SDK provides a list of route segments. In addition, the driver can swipe through the directions card in the header to see each maneuver.
How is ETA communicated to the app users?

In Android, use the following steps to give ETA information to app users:

  1. Retrieve the time and distance for all waypoints using Navigator.getTimeAndDistanceList() .
  2. Forward this information to the client application as you do for the driver ETA.

In iOS, use these steps to give ETA information to app users:

  1. Retrieve the legs in the journey using Navigator.getRouteSegments() .
  2. Call GMSNavigator.timeToNextDestination for each journey leg.
  3. Forward the time information to the client application as you do for the driver ETA.
Can the RoadSnappedLocationProvider be used to obtain the driver's current snapped location if navigation is not in the foreground?

Yes. In Android, the RoadSnappedLocationProvider runs in the background by default.

In iOS, to keep navigation running in the background, implement the listener for GMSRoadSnappedLocationProviderListener , and set the property allowsBackgroundLocationUpdates to TRUE .

Does the Navigation SDK support geofencing?

No. In the context of navigation, remainingTimeOrdistanceChangeListener has an advantage over a geofence. The geofence might not account for road geometry, and might not be centered on the exact point to which the driver is navigating.

You can approximate this functionality using remainingTimeOrdistanceChangeListener .

  1. Set the threshold to determine the frequency of the callbacks.
  2. Check the remaining distance to the destination.

For example, if you set the threshold to 100m, you receive a callback when the distance to the destination changes by 100m. As the distance decreases, you can update this threshold to a smaller value and receive more frequent callbacks. Then, inspect the remaining distance to determine if you are close enough to the pickup/drop-off location.

In iOS, implement the listener GMSNavigatorListener.didUpdateRemainingDistance to manage the distance between notifications.

Can I disable notifications when the Navigation app is in the background?

Yes. In Android, use Navigator.setHeadsUpNotificationEnabled to control notifications. This method has a boolean argument. FALSE disables notifications; TRUE enables notifications.

In iOS, disable background notification for road-snapped locations by setting GMSRoadSnappedLocationProvider.allowsBackgroundLocationUpdates to NO.

To disable background processing for other location notifications, call GMSNavigator.sendsBackgroundNotifications(NO) .

UI Customization

Can I color code the best route option?
No. Color coding a specific route option is not supported at this time.
Can the Navigation SDK show the ETA for the final destination?

Yes. In Android, use the following methods:

  1. Retrieve the time and distance for all waypoints using Navigator.getTimeAndDistanceList() .
  2. Hide the ETA of the current waypoint using NavigationFragment.setEtaCardEnabled(false) .
  3. Render the final destination ETA.

In iOS, use the following:

  1. Call GMSNavigator.routeLegs(read) .
  2. With the last leg, call GMSNavigator.timeToNextDestination .
  3. Hide the ETA of the current waypoint using MSMapView.settings.navigationFooterEnabled=NO to FALSE.
  4. Render the final destination ETA.
How can I hide ETA updates?

You can disable ETA cards with the following methods:

  • In Android, use navigationView.setEtaCardEnabled(false) .
  • In iOS, use GMSMapView.settings.navigationFooterEnabled=NO .
Which UI customizations are available for the header and footer cards?

In Android, you use StylingOptions to set the background color styling. To hide or show the header and footer, use the setHeaderEnabled and setFooterEnabled member functions of NavigationFragment .

In iOS, use GMSMapView.settings.navigationHeaderPrimaryBackgroundColor to set the background color styling. To hide or show the header and footer use navigationFooterEnabled and navigationHeaderEnabled properties of GMSUISettings .

Маршрутизация

Can I provide a specific route to a driver or remove alternative routes?
No. By default, multiple routes are provided and the fastest route has priority. You can affect the default route by adding preferences, such as "avoid highways and tolls," to your request. Adding waypoints also affects the route.
Can I show the app user a different label for the destination than the default destination location?

Yes. In Android, create a Marker with a custom title for the destination and the latitude/longitude. The Navigation SDK displays the custom title and the coordinates on the NavigationMap .

In iOS, you create and display a GMSMarker for the destination.

Can I use the Navigation SDK to track deviations from a defined path?

Yes. In Android, use Navigator.setRouteChangedListener to receive notifications when a route changes or a new route is recommended:

  1. Register a listener that checks the device position along the route using the Navigator.setRouteChangedListener method.
  2. Add code to the callback event handler, onRouteChanged :
    • Send a message to the app user with updated ETA and distance information.
    • Track the device's location.
    • [optional] Add other functionality required by your app to handle when the driver is off the prescribed route.

In iOS, use the GMSNavigator and its listeners to receive notifications when a route changes or a new route is recommended:

  1. On the map's view controller, implement the GMSNavigatorListener protocol and the GMSRoadSnappedLocationProviderListener protocol.
  2. Implement GMSNavigatorListener.navigatorDidChangeRoute .
  3. Access the new route using routeLegs and currentRouteLeg properties of the GMSNavigator .
Can the driver exit navigation without completing the route?

Yes. In Android, call the Navigator.stopGuidance() method to stop navigation.

In iOS, call GMSNavigator.clearDestinations .

Симулятор

Does the simulator support route changes?

Yes. In Android, call simulateLocationsAlongNewRoute to simulate a journey that includes a route change. The simulateLocationsAlongExistingRoute method ignores changes to the existing route.

In iOS, use GMSLocationSimulator.simulateAlongNewRouteToDestinations to simulate a journey that includes a route change. If you don't anticipate any route changes, you can use GMSLocationSimulator.simulateLocationsAlongExistingRoute or GMSLocationSimulator.simulateAlongNewRouteToDestinations .

Рабочие процессы

How do I dismiss the notification after closing an activity that contains a navigation fragment?

The navigation notification remains visible during navigation, when the activity is closed. When the vehicle arrives at the destination, navigation stops, and the notification disappears.

To handle clicks on the notification, use the Navigator.startGuidance(intent resumeIntent) . The resume intent fires when the app user clicks the notification. Typically, the Navigator.startguidance(getIntent()) is called from the main Activity, which recalls the Activity when the app user clicks the notification.

Услуги мобильности

How is using the Navigation SDK different for Mobility Services customers?

Google Maps Platform Mobility Services offer a collection of APIs and SDKs to help support enterprise needs for transportation and logistics businesses. For Mobility Services customers, the Navigation SDK is typically used in conjunction with related services for route optimization, dispatch, task tracking, fleet analytics, and more. The Navigation SDK is also billed differently for Mobility Services customers. For more information, see the Mobility Services documentation.

Mobility products are available only to select customers. Contact your sales representative for more information.

How can I tell if I'm a Mobility Services customer?
If you're not sure if you're implementing the Navigation SDK as a Mobility Services customer, look for a ReportBillableEvent call in your code. Only Mobility Services customers should call the ReportBillableEvent method.

How is the Navigation SDK billed for Mobility Services customers?
For Mobility Services customers, billing and pricing for the Navigation SDK depend on the service agreement you have with Google Maps Platform. For information on verifying that your Mobility Services implementation is being billed correctly see Billing validation . For additional information about Mobility Services billing, contact your sales representative.

Which Navigation SDK APIs should only be used by Mobility Services customers?

There are several APIs in the Navigation SDK that are only intended for use by Mobility Services customers, who are billed by Google on a per-transaction basis. If you are not a Mobility Services customer, the following methods are no-ops:

If I'm a Mobility Services customer, can I also use a non-Mobility Services implementation of the Navigation SDK?

Yes, Mobility Services customers can use both Mobility Services and non-Mobility Services implementations of the Navigation SDK. However, you can only use one implementation type in an app at one time. You also need to create a new Google Cloud project, billing account, and API key, separate from those that you use with your Mobility Services implementation. For more information, see the Navigation SDK setup overview .

For more information about using a non-Mobility Services implementation of the Navigation SDK, including migrating an app from one implementation type to the other, contact your Google account representative.

Note: If you are not a Mobility Services customer and are interested in learning more about the Mobility Services collection of APIs and SDKs, contact Google Maps Platform sales .

,

Часто задаваемые вопросы

Подробная информация о товаре

Проблемы

Сеть

Данные

UI Customization

Маршрутизация

Симулятор

Рабочие процессы

Услуги мобильности

Подробная информация о товаре

Your app must implement a dialog with the Navigation SDK Terms of Service notice that each driver must accept. This dialog gives the driver the opportunity to agree with the Terms of Service. A text file of the terms is provided with the Navigation SDK.
In Android, use the NavigationApi.showTermsAndConditionsDialog method to display the dialog containing the terms.
In iOS, call GMSNavigationServices.showTermsAndConditionsDialogIfNeededWithCompanyName .
Any languages supported by Google Maps Mobile are automatically available for the Navigation SDK. A device has a default system language and an app cannot change that setting; however, the app has access to over 70 languages.

Yes. In Android, once started, the LocationListener continues to run in the background. Your app continues road snapping the position and maintains the bearing.

In iOS, to continue receiving location updates of position and bearing in the background, implement road snapping and set allowsBackgroundLocationUpdates to YES .

Yes. When a route is created or changed, the RouteChangeListener provides polylines.

No, the Navigation SDK does not require Google Maps Mobile to be installed on the device.
No, the Navigation SDK does not provide this functionality at this time.
Yes. The traffic direction is available and displayed by default.

Проблемы

In Xcode 12, apps don't build correctly for the simulator. How can I fix this?

To fix this issue, open your Xcode project Build Settings, and add arm64 to the Excluded Architectures for "iOS Simulator" builds only.

For more information, see the following StackOverflow thread .

GMSMapView does not load.

If the GMSMapView does not load:

  • Check that NavSDK is enabled in Cloud Console.
  • If the Nav SDK is installed, but your project does not use Nav SDK APIs, remove it from your binary.

Сеть

How does the Navigation SDK handle poor connectivity?
The Navigation SDK pre-caches the route for each journey. The pre-cached information includes routing information for 15-20 minutes, and route alternatives in case the driver deviates from the route. The Navigation SDK approximates position using the device GPS and sensors.
Is an offline mode available?
No, the Navigation SDK does not offer an offline mode at this time; however, the SDK does provide pre-cached information for a journey.

Данные

Can I retrieve all of the stops/destinations in a journey before starting the route?

Yes. In Android, to retrieve the directions for a route, call Navigator.getRouteSegments() .

In iOS, call GMSNavigator.routeLegs(read) .

Is turn-by-turn route guidance available at the start of a route?
Yes. The Navigation SDK provides a list of route segments. In addition, the driver can swipe through the directions card in the header to see each maneuver.
How is ETA communicated to the app users?

In Android, use the following steps to give ETA information to app users:

  1. Retrieve the time and distance for all waypoints using Navigator.getTimeAndDistanceList() .
  2. Forward this information to the client application as you do for the driver ETA.

In iOS, use these steps to give ETA information to app users:

  1. Retrieve the legs in the journey using Navigator.getRouteSegments() .
  2. Call GMSNavigator.timeToNextDestination for each journey leg.
  3. Forward the time information to the client application as you do for the driver ETA.
Can the RoadSnappedLocationProvider be used to obtain the driver's current snapped location if navigation is not in the foreground?

Yes. In Android, the RoadSnappedLocationProvider runs in the background by default.

In iOS, to keep navigation running in the background, implement the listener for GMSRoadSnappedLocationProviderListener , and set the property allowsBackgroundLocationUpdates to TRUE .

Does the Navigation SDK support geofencing?

No. In the context of navigation, remainingTimeOrdistanceChangeListener has an advantage over a geofence. The geofence might not account for road geometry, and might not be centered on the exact point to which the driver is navigating.

You can approximate this functionality using remainingTimeOrdistanceChangeListener .

  1. Set the threshold to determine the frequency of the callbacks.
  2. Check the remaining distance to the destination.

For example, if you set the threshold to 100m, you receive a callback when the distance to the destination changes by 100m. As the distance decreases, you can update this threshold to a smaller value and receive more frequent callbacks. Then, inspect the remaining distance to determine if you are close enough to the pickup/drop-off location.

In iOS, implement the listener GMSNavigatorListener.didUpdateRemainingDistance to manage the distance between notifications.

Can I disable notifications when the Navigation app is in the background?

Yes. In Android, use Navigator.setHeadsUpNotificationEnabled to control notifications. This method has a boolean argument. FALSE disables notifications; TRUE enables notifications.

In iOS, disable background notification for road-snapped locations by setting GMSRoadSnappedLocationProvider.allowsBackgroundLocationUpdates to NO.

To disable background processing for other location notifications, call GMSNavigator.sendsBackgroundNotifications(NO) .

UI Customization

Can I color code the best route option?
No. Color coding a specific route option is not supported at this time.
Can the Navigation SDK show the ETA for the final destination?

Yes. In Android, use the following methods:

  1. Retrieve the time and distance for all waypoints using Navigator.getTimeAndDistanceList() .
  2. Hide the ETA of the current waypoint using NavigationFragment.setEtaCardEnabled(false) .
  3. Render the final destination ETA.

In iOS, use the following:

  1. Call GMSNavigator.routeLegs(read) .
  2. With the last leg, call GMSNavigator.timeToNextDestination .
  3. Hide the ETA of the current waypoint using MSMapView.settings.navigationFooterEnabled=NO to FALSE.
  4. Render the final destination ETA.
How can I hide ETA updates?

You can disable ETA cards with the following methods:

  • In Android, use navigationView.setEtaCardEnabled(false) .
  • In iOS, use GMSMapView.settings.navigationFooterEnabled=NO .
Which UI customizations are available for the header and footer cards?

In Android, you use StylingOptions to set the background color styling. To hide or show the header and footer, use the setHeaderEnabled and setFooterEnabled member functions of NavigationFragment .

In iOS, use GMSMapView.settings.navigationHeaderPrimaryBackgroundColor to set the background color styling. To hide or show the header and footer use navigationFooterEnabled and navigationHeaderEnabled properties of GMSUISettings .

Маршрутизация

Can I provide a specific route to a driver or remove alternative routes?
No. By default, multiple routes are provided and the fastest route has priority. You can affect the default route by adding preferences, such as "avoid highways and tolls," to your request. Adding waypoints also affects the route.
Can I show the app user a different label for the destination than the default destination location?

Yes. In Android, create a Marker with a custom title for the destination and the latitude/longitude. The Navigation SDK displays the custom title and the coordinates on the NavigationMap .

In iOS, you create and display a GMSMarker for the destination.

Can I use the Navigation SDK to track deviations from a defined path?

Yes. In Android, use Navigator.setRouteChangedListener to receive notifications when a route changes or a new route is recommended:

  1. Register a listener that checks the device position along the route using the Navigator.setRouteChangedListener method.
  2. Add code to the callback event handler, onRouteChanged :
    • Send a message to the app user with updated ETA and distance information.
    • Track the device's location.
    • [optional] Add other functionality required by your app to handle when the driver is off the prescribed route.

In iOS, use the GMSNavigator and its listeners to receive notifications when a route changes or a new route is recommended:

  1. On the map's view controller, implement the GMSNavigatorListener protocol and the GMSRoadSnappedLocationProviderListener protocol.
  2. Implement GMSNavigatorListener.navigatorDidChangeRoute .
  3. Access the new route using routeLegs and currentRouteLeg properties of the GMSNavigator .
Can the driver exit navigation without completing the route?

Yes. In Android, call the Navigator.stopGuidance() method to stop navigation.

In iOS, call GMSNavigator.clearDestinations .

Симулятор

Does the simulator support route changes?

Yes. In Android, call simulateLocationsAlongNewRoute to simulate a journey that includes a route change. The simulateLocationsAlongExistingRoute method ignores changes to the existing route.

In iOS, use GMSLocationSimulator.simulateAlongNewRouteToDestinations to simulate a journey that includes a route change. If you don't anticipate any route changes, you can use GMSLocationSimulator.simulateLocationsAlongExistingRoute or GMSLocationSimulator.simulateAlongNewRouteToDestinations .

Рабочие процессы

How do I dismiss the notification after closing an activity that contains a navigation fragment?

The navigation notification remains visible during navigation, when the activity is closed. When the vehicle arrives at the destination, navigation stops, and the notification disappears.

To handle clicks on the notification, use the Navigator.startGuidance(intent resumeIntent) . The resume intent fires when the app user clicks the notification. Typically, the Navigator.startguidance(getIntent()) is called from the main Activity, which recalls the Activity when the app user clicks the notification.

Услуги мобильности

How is using the Navigation SDK different for Mobility Services customers?

Google Maps Platform Mobility Services offer a collection of APIs and SDKs to help support enterprise needs for transportation and logistics businesses. For Mobility Services customers, the Navigation SDK is typically used in conjunction with related services for route optimization, dispatch, task tracking, fleet analytics, and more. The Navigation SDK is also billed differently for Mobility Services customers. For more information, see the Mobility Services documentation.

Mobility products are available only to select customers. Contact your sales representative for more information.

How can I tell if I'm a Mobility Services customer?
If you're not sure if you're implementing the Navigation SDK as a Mobility Services customer, look for a ReportBillableEvent call in your code. Only Mobility Services customers should call the ReportBillableEvent method.

How is the Navigation SDK billed for Mobility Services customers?
For Mobility Services customers, billing and pricing for the Navigation SDK depend on the service agreement you have with Google Maps Platform. For information on verifying that your Mobility Services implementation is being billed correctly see Billing validation . For additional information about Mobility Services billing, contact your sales representative.

Which Navigation SDK APIs should only be used by Mobility Services customers?

There are several APIs in the Navigation SDK that are only intended for use by Mobility Services customers, who are billed by Google on a per-transaction basis. If you are not a Mobility Services customer, the following methods are no-ops:

If I'm a Mobility Services customer, can I also use a non-Mobility Services implementation of the Navigation SDK?

Yes, Mobility Services customers can use both Mobility Services and non-Mobility Services implementations of the Navigation SDK. However, you can only use one implementation type in an app at one time. You also need to create a new Google Cloud project, billing account, and API key, separate from those that you use with your Mobility Services implementation. For more information, see the Navigation SDK setup overview .

For more information about using a non-Mobility Services implementation of the Navigation SDK, including migrating an app from one implementation type to the other, contact your Google account representative.

Note: If you are not a Mobility Services customer and are interested in learning more about the Mobility Services collection of APIs and SDKs, contact Google Maps Platform sales .