Автозаполнение мест

The autocomplete service in the Places SDK for iOS returns place predictions in response to user search queries. As the user types, the autocomplete service returns suggestions for places such as businesses, addresses, plus codes and points of interest.

Добавить функцию автозаполнения в приложение можно следующими способами:

Добавление элемента управления автозаполнения в пользовательский интерфейс.

The autocomplete UI control is a search dialog with built-in autocomplete functionality. As a user enters search terms, the control presents a list of predicted places to choose from. When the user makes a selection, a GMSPlace instance is returned, which your app can then use to get details about the selected place.

Добавить элемент управления автозаполнением в ваше приложение можно следующими способами:

Добавление элемента управления полноэкранным режимом

Use the full-screen control when you want a modal context, where the autocomplete UI temporarily replaces the UI of your app until the user has made their selection. This functionality is provided by the GMSAutocompleteViewController class. When the user selects a place, your app receives a callback.

Чтобы добавить в приложение полноэкранный режим:

  1. Создайте в основном приложении элемент пользовательского интерфейса для запуска автозаполнения, например, обработчик касания на UIButton .
  2. Реализуйте протокол GMSAutocompleteViewControllerDelegate в родительском контроллере представления.
  3. Создайте экземпляр GMSAutocompleteViewController и назначьте родительский контроллер представления в качестве свойства делегата.
  4. Создайте объект GMSPlaceField , чтобы определить типы данных о местах, которые будут возвращаться.
  5. Добавьте GMSAutocompleteFilter , чтобы ограничить запрос определенным типом места .
  6. Отобразите GMSAutocompleteViewController с помощью [self presentViewController...] .
  7. Обработайте выбор пользователя в методе делегата didAutocompleteWithPlace .
  8. Закройте контроллер в методах делегата didAutocompleteWithPlace , didFailAutocompleteWithError и wasCancelled .

В следующем примере показан один из возможных способов запуска GMSAutocompleteViewController в ответ на нажатие пользователем кнопки.

Быстрый

import UIKit
import GooglePlaces

class ViewController: UIViewController {

  override func viewDidLoad() {
    makeButton()
  }

  // Present the Autocomplete view controller when the button is pressed.
  @objc func autocompleteClicked(_ sender: UIButton) {
    let autocompleteController = GMSAutocompleteViewController()
    autocompleteController.delegate = self

    // Specify the place data types to return.
    let fields: GMSPlaceField = GMSPlaceField(rawValue: UInt(GMSPlaceField.name.rawValue) |
      UInt(GMSPlaceField.placeID.rawValue))!
    autocompleteController.placeFields = fields

    // Specify a filter.
    let filter = GMSAutocompleteFilter()
    filter.types = [kGMSPlaceTypeCollectionAddress]
    autocompleteController.autocompleteFilter = filter

    // Display the autocomplete view controller.
    present(autocompleteController, animated: true, completion: nil)
  }

  // Add a button to the view.
  func makeButton() {
    let btnLaunchAc = UIButton(frame: CGRect(x: 5, y: 150, width: 300, height: 35))
    btnLaunchAc.backgroundColor = .blue
    btnLaunchAc.setTitle("Launch autocomplete", for: .normal)
    btnLaunchAc.addTarget(self, action: #selector(autocompleteClicked), for: .touchUpInside)
    self.view.addSubview(btnLaunchAc)
  }

}

extension ViewController: GMSAutocompleteViewControllerDelegate {

  // Handle the user's selection.
  func viewController(_ viewController: GMSAutocompleteViewController, didAutocompleteWith place: GMSPlace) {
    print("Place name: \(place.name)")
    print("Place ID: \(place.placeID)")
    print("Place attributions: \(place.attributions)")
    dismiss(animated: true, completion: nil)
  }

  func viewController(_ viewController: GMSAutocompleteViewController, didFailAutocompleteWithError error: Error) {
    // TODO: handle the error.
    print("Error: ", error.localizedDescription)
  }

  // User canceled the operation.
  func wasCancelled(_ viewController: GMSAutocompleteViewController) {
    dismiss(animated: true, completion: nil)
  }

  // Turn the network activity indicator on and off again.
  func didRequestAutocompletePredictions(_ viewController: GMSAutocompleteViewController) {
    UIApplication.shared.isNetworkActivityIndicatorVisible = true
  }

  func didUpdateAutocompletePredictions(_ viewController: GMSAutocompleteViewController) {
    UIApplication.shared.isNetworkActivityIndicatorVisible = false
  }

}

Objective-C

#import "ViewController.h"
@import GooglePlaces;

@interface ViewController () <GMSAutocompleteViewControllerDelegate>

@end

@implementation ViewController {
  GMSAutocompleteFilter *_filter;
}

-   (void)viewDidLoad {
  [super viewDidLoad];
  [self makeButton];
}

  // Present the autocomplete view controller when the button is pressed.
-   (void)autocompleteClicked {
  GMSAutocompleteViewController *acController = [[GMSAutocompleteViewController alloc] init];
  acController.delegate = self;

  // Specify the place data types to return.
  GMSPlaceField fields = (GMSPlaceFieldName | GMSPlaceFieldPlaceID);
  acController.placeFields = fields;

  // Specify a filter.
  _filter = [[GMSAutocompleteFilter alloc] init];
  _filter.types = @[ kGMSPlaceTypeBank ];
  acController.autocompleteFilter = _filter;

  // Display the autocomplete view controller.
  [self presentViewController:acController animated:YES completion:nil];
}

  // Add a button to the view.
-   (void)makeButton{
  UIButton *btnLaunchAc = [UIButton buttonWithType:UIButtonTypeCustom];
  [btnLaunchAc addTarget:self
             action:@selector(autocompleteClicked) forControlEvents:UIControlEventTouchUpInside];
  [btnLaunchAc setTitle:@"Launch autocomplete" forState:UIControlStateNormal];
  btnLaunchAc.frame = CGRectMake(5.0, 150.0, 300.0, 35.0);
  btnLaunchAc.backgroundColor = [UIColor blueColor];
  [self.view addSubview:btnLaunchAc];
}

  // Handle the user's selection.
-   (void)viewController:(GMSAutocompleteViewController *)viewController
didAutocompleteWithPlace:(GMSPlace *)place {
  [self dismissViewControllerAnimated:YES completion:nil];
  // Do something with the selected place.
  NSLog(@"Place name %@", place.name);
  NSLog(@"Place ID %@", place.placeID);
  NSLog(@"Place attributions %@", place.attributions.string);
}

-   (void)viewController:(GMSAutocompleteViewController *)viewController
didFailAutocompleteWithError:(NSError *)error {
  [self dismissViewControllerAnimated:YES completion:nil];
  // TODO: handle the error.
  NSLog(@"Error: %@", [error description]);
}

  // User canceled the operation.
-   (void)wasCancelled:(GMSAutocompleteViewController *)viewController {
  [self dismissViewControllerAnimated:YES completion:nil];
}

  // Turn the network activity indicator on and off again.
-   (void)didRequestAutocompletePredictions:(GMSAutocompleteViewController *)viewController {
  [UIApplication sharedApplication].networkActivityIndicatorVisible = YES;
}

-   (void)didUpdateAutocompletePredictions:(GMSAutocompleteViewController *)viewController {
  [UIApplication sharedApplication].networkActivityIndicatorVisible = NO;
}

@end

Добавление контроллера результатов

Используйте контроллер результатов, если вам нужен больший контроль над пользовательским интерфейсом текстового поля ввода. Контроллер результатов динамически переключает видимость списка результатов в зависимости от фокуса поля ввода.

Чтобы добавить контроллер результатов в ваше приложение:

  1. Создайте контроллер представления GMSAutocompleteResultsViewController .
    1. Реализуйте протокол GMSAutocompleteResultsViewControllerDelegate в родительском контроллере представления и назначьте родительский контроллер представления в качестве свойства делегата.
  2. Создайте объект UISearchController , передав в качестве аргумента контроллера результатов объект GMSAutocompleteResultsViewController .
  3. Установите свойство searchResultsUpdater контроллера UISearchController в качестве свойства GMSAutocompleteResultsViewController .
  4. Добавьте строку searchBar для UISearchController в пользовательский интерфейс вашего приложения.
  5. Обработайте выбор пользователя в методе делегата didAutocompleteWithPlace .

Существует несколько способов разместить строку поиска из UISearchController в пользовательском интерфейсе вашего приложения:

Добавление строки поиска в панель навигации.

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

Быстрый

class ViewController: UIViewController {

  var resultsViewController: GMSAutocompleteResultsViewController?
  var searchController: UISearchController?
  var resultView: UITextView?

  override func viewDidLoad() {
    super.viewDidLoad()

    resultsViewController = GMSAutocompleteResultsViewController()
    resultsViewController?.delegate = self

    searchController = UISearchController(searchResultsController: resultsViewController)
    searchController?.searchResultsUpdater = resultsViewController

    // Put the search bar in the navigation bar.
    searchController?.searchBar.sizeToFit()
    navigationItem.titleView = searchController?.searchBar

    // When UISearchController presents the results view, present it in
    // this view controller, not one further up the chain.
    definesPresentationContext = true

    // Prevent the navigation bar from being hidden when searching.
    searchController?.hidesNavigationBarDuringPresentation = false
  }
}

// Handle the user's selection.
extension ViewController: GMSAutocompleteResultsViewControllerDelegate {
  func resultsController(_ resultsController: GMSAutocompleteResultsViewController,
                         didAutocompleteWith place: GMSPlace) {
    searchController?.isActive = false
    // Do something with the selected place.
    print("Place name: \(place.name)")
    print("Place address: \(place.formattedAddress)")
    print("Place attributions: \(place.attributions)")
  }

  func resultsController(_ resultsController: GMSAutocompleteResultsViewController,
                         didFailAutocompleteWithError error: Error){
    // TODO: handle the error.
    print("Error: ", error.localizedDescription)
  }

  // Turn the network activity indicator on and off again.
  func didRequestAutocompletePredictions(_ viewController: GMSAutocompleteViewController) {
    UIApplication.shared.isNetworkActivityIndicatorVisible = true
  }

  func didUpdateAutocompletePredictions(_ viewController: GMSAutocompleteViewController) {
    UIApplication.shared.isNetworkActivityIndicatorVisible = false
  }
}

Objective-C

-   (void)viewDidLoad {
  _resultsViewController = [[GMSAutocompleteResultsViewController alloc] init];
  _resultsViewController.delegate = self;

  _searchController = [[UISearchController alloc]
                       initWithSearchResultsController:_resultsViewController];
  _searchController.searchResultsUpdater = _resultsViewController;

  // Put the search bar in the navigation bar.
  [_searchController.searchBar sizeToFit];
  self.navigationItem.titleView = _searchController.searchBar;

  // When UISearchController presents the results view, present it in
  // this view controller, not one further up the chain.
  self.definesPresentationContext = YES;

  // Prevent the navigation bar from being hidden when searching.
  _searchController.hidesNavigationBarDuringPresentation = NO;
}

// Handle the user's selection.
-   (void)resultsController:(GMSAutocompleteResultsViewController *)resultsController
  didAutocompleteWithPlace:(GMSPlace *)place {
    _searchController.active = NO;
    // Do something with the selected place.
    NSLog(@"Place name %@", place.name);
    NSLog(@"Place address %@", place.formattedAddress);
    NSLog(@"Place attributions %@", place.attributions.string);
}

-   (void)resultsController:(GMSAutocompleteResultsViewController *)resultsController
didFailAutocompleteWithError:(NSError *)error {
  [self dismissViewControllerAnimated:YES completion:nil];
  // TODO: handle the error.
  NSLog(@"Error: %@", [error description]);
}

// Turn the network activity indicator on and off again.
-   (void)didRequestAutocompletePredictionsForResultsController:
    (GMSAutocompleteResultsViewController *)resultsController {
  [UIApplication sharedApplication].networkActivityIndicatorVisible = YES;
}

-   (void)didUpdateAutocompletePredictionsForResultsController:
    (GMSAutocompleteResultsViewController *)resultsController {
  [UIApplication sharedApplication].networkActivityIndicatorVisible = NO;
}

Добавление строки поиска в верхнюю часть экрана

В следующем примере кода показано добавление строки searchBar в верхнюю часть представления.

Быстрый

import UIKit
import GooglePlaces

class ViewController: UIViewController {

  var resultsViewController: GMSAutocompleteResultsViewController?
  var searchController: UISearchController?
  var resultView: UITextView?

  override func viewDidLoad() {
    super.viewDidLoad()

    resultsViewController = GMSAutocompleteResultsViewController()
    resultsViewController?.delegate = self

    searchController = UISearchController(searchResultsController: resultsViewController)
    searchController?.searchResultsUpdater = resultsViewController

    let subView = UIView(frame: CGRect(x: 0, y: 65.0, width: 350.0, height: 45.0))

    subView.addSubview((searchController?.searchBar)!)
    view.addSubview(subView)
    searchController?.searchBar.sizeToFit()
    searchController?.hidesNavigationBarDuringPresentation = false

    // When UISearchController presents the results view, present it in
    // this view controller, not one further up the chain.
    definesPresentationContext = true
  }
}

// Handle the user's selection.
extension ViewController: GMSAutocompleteResultsViewControllerDelegate {
  func resultsController(_ resultsController: GMSAutocompleteResultsViewController,
                         didAutocompleteWith place: GMSPlace) {
    searchController?.isActive = false
    // Do something with the selected place.
    print("Place name: \(place.name)")
    print("Place address: \(place.formattedAddress)")
    print("Place attributions: \(place.attributions)")
  }

  func resultsController(_ resultsController: GMSAutocompleteResultsViewController,
                         didFailAutocompleteWithError error: Error){
    // TODO: handle the error.
    print("Error: ", error.localizedDescription)
  }

  // Turn the network activity indicator on and off again.
  func didRequestAutocompletePredictions(forResultsController resultsController: GMSAutocompleteResultsViewController) {
    UIApplication.shared.isNetworkActivityIndicatorVisible = true
  }

  func didUpdateAutocompletePredictions(forResultsController resultsController: GMSAutocompleteResultsViewController) {
    UIApplication.shared.isNetworkActivityIndicatorVisible = false
  }
}

Objective-C

-   (void)viewDidLoad {
    [super viewDidLoad];

    _resultsViewController = [[GMSAutocompleteResultsViewController alloc] init];
    _resultsViewController.delegate = self;

    _searchController = [[UISearchController alloc]
                             initWithSearchResultsController:_resultsViewController];
    _searchController.searchResultsUpdater = _resultsViewController;

    UIView *subView = [[UIView alloc] initWithFrame:CGRectMake(0, 65.0, 250, 50)];

    [subView addSubview:_searchController.searchBar];
    [_searchController.searchBar sizeToFit];
    [self.view addSubview:subView];

    // When UISearchController presents the results view, present it in
    // this view controller, not one further up the chain.
    self.definesPresentationContext = YES;
}

// Handle the user's selection.
-   (void)resultsController:(GMSAutocompleteResultsViewController *)resultsController
didAutocompleteWithPlace:(GMSPlace *)place {
  [self dismissViewControllerAnimated:YES completion:nil];
  // Do something with the selected place.
  NSLog(@"Place name %@", place.name);
  NSLog(@"Place address %@", place.formattedAddress);
  NSLog(@"Place attributions %@", place.attributions.string);
}

-   (void)resultsController:(GMSAutocompleteResultsViewController *)resultsController
didFailAutocompleteWithError:(NSError *)error {
  [self dismissViewControllerAnimated:YES completion:nil];
  // TODO: handle the error.
  NSLog(@"Error: %@", [error description]);
}

// Turn the network activity indicator on and off again.
-   (void)didRequestAutocompletePredictionsForResultsController:
    (GMSAutocompleteResultsViewController *)resultsController {
  [UIApplication sharedApplication].networkActivityIndicatorVisible = YES;
}

-   (void)didUpdateAutocompletePredictionsForResultsController:
    (GMSAutocompleteResultsViewController *)resultsController {
  [UIApplication sharedApplication].networkActivityIndicatorVisible = NO;
}

By default, UISearchController hides the navigation bar when presenting (this can be disabled). In cases where the navigation bar is visible and opaque, UISearchController does not set the placement correctly.

В качестве обходного решения воспользуйтесь следующим кодом:

Быстрый

navigationController?.navigationBar.translucent = false
searchController?.hidesNavigationBarDuringPresentation = false

// This makes the view area include the nav bar even though it is opaque.
// Adjust the view placement down.
self.extendedLayoutIncludesOpaqueBars = true
self.edgesForExtendedLayout = .top

Objective-C

self.navigationController.navigationBar.translucent = NO;
_searchController.hidesNavigationBarDuringPresentation = NO;

// This makes the view area include the nav bar even though it is opaque.
// Adjust the view placement down.
self.extendedLayoutIncludesOpaqueBars = YES;
self.edgesForExtendedLayout = UIRectEdgeTop;

Добавление строки поиска с использованием всплывающих результатов

В следующем примере кода показано размещение строки поиска справа от панели навигации и отображение результатов во всплывающем окне.

Быстрый

import UIKit
import GooglePlaces

class ViewController: UIViewController {

  var resultsViewController: GMSAutocompleteResultsViewController?
  var searchController: UISearchController?
  var resultView: UITextView?

  override func viewDidLoad() {
    super.viewDidLoad()

    resultsViewController = GMSAutocompleteResultsViewController()
    resultsViewController?.delegate = self

    searchController = UISearchController(searchResultsController: resultsViewController)
    searchController?.searchResultsUpdater = resultsViewController

    // Add the search bar to the right of the nav bar,
    // use a popover to display the results.
    // Set an explicit size as we don't want to use the entire nav bar.
    searchController?.searchBar.frame = (CGRect(x: 0, y: 0, width: 250.0, height: 44.0))
    navigationItem.rightBarButtonItem = UIBarButtonItem(customView: (searchController?.searchBar)!)

    // When UISearchController presents the results view, present it in
    // this view controller, not one further up the chain.
    definesPresentationContext = true

    // Keep the navigation bar visible.
    searchController?.hidesNavigationBarDuringPresentation = false
    searchController?.modalPresentationStyle = .popover
  }
}
// Handle the user's selection.
extension ViewController: GMSAutocompleteResultsViewControllerDelegate {
  func resultsController(_ resultsController: GMSAutocompleteResultsViewController,
                         didAutocompleteWith place: GMSPlace) {
    searchController?.isActive = false
    // Do something with the selected place.
    print("Place name: \(place.name)")
    print("Place address: \(place.formattedAddress)")
    print("Place attributions: \(place.attributions)")
  }

  func resultsController(_ resultsController: GMSAutocompleteResultsViewController,
                         didFailAutocompleteWithError error: Error){
    // TODO: handle the error.
    print("Error: ", error.localizedDescription)
  }

  // Turn the network activity indicator on and off again.
  func didRequestAutocompletePredictions(forResultsController resultsController: GMSAutocompleteResultsViewController) {
    UIApplication.shared.isNetworkActivityIndicatorVisible = true
  }

  func didUpdateAutocompletePredictions(forResultsController resultsController: GMSAutocompleteResultsViewController) {
    UIApplication.shared.isNetworkActivityIndicatorVisible = false
  }
}

Objective-C

-   (void)viewDidLoad {
  [super viewDidLoad];

  _resultsViewController = [[GMSAutocompleteResultsViewController alloc] init];
  _resultsViewController.delegate = self;

  _searchController = [[UISearchController alloc]
                           initWithSearchResultsController:_resultsViewController];
  _searchController.searchResultsUpdater = _resultsViewController;

  // Add the search bar to the right of the nav bar,
  // use a popover to display the results.
  // Set an explicit size as we don't want to use the entire nav bar.
  _searchController.searchBar.frame = CGRectMake(0, 0, 250.0f, 44.0f);
  self.navigationItem.rightBarButtonItem =
  [[UIBarButtonItem alloc] initWithCustomView:_searchController.searchBar];

  // When UISearchController presents the results view, present it in
  // this view controller, not one further up the chain.
  self.definesPresentationContext = YES;

  // Keep the navigation bar visible.
  _searchController.hidesNavigationBarDuringPresentation = NO;

  _searchController.modalPresentationStyle = UIModalPresentationPopover;
}

// Handle the user's selection.
-   (void)resultsController:(GMSAutocompleteResultsViewController *)resultsController
didAutocompleteWithPlace:(GMSPlace *)place {
  [self dismissViewControllerAnimated:YES completion:nil];
  NSLog(@"Place name %@", place.name);
  NSLog(@"Place address %@", place.formattedAddress);
  NSLog(@"Place attributions %@", place.attributions.string);
}

-   (void)resultsController:(GMSAutocompleteResultsViewController *)resultsController
didFailAutocompleteWithError:(NSError *)error {
  [self dismissViewControllerAnimated:YES completion:nil];
  // TODO: handle the error.
  NSLog(@"Error: %@", [error description]);
}

// Turn the network activity indicator on and off again.
-   (void)didRequestAutocompletePredictionsForResultsController:
    (GMSAutocompleteResultsViewController *)resultsController {
  [UIApplication sharedApplication].networkActivityIndicatorVisible = YES;
}

-   (void)didUpdateAutocompletePredictionsForResultsController:
    (GMSAutocompleteResultsViewController *)resultsController {
  [UIApplication sharedApplication].networkActivityIndicatorVisible = NO;
}

Использование табличного источника данных

Если в вашем приложении есть собственный текстовый интерфейс поиска, вы можете использовать класс GMSAutocompleteTableDataSource для управления табличным представлением, отображающим результаты в контроллере представления.

Чтобы использовать GMSAutocompleteTableDataSource в качестве источника данных и делегата для UITableView в контроллере представления:

  1. Реализуйте протоколы GMSAutocompleteTableDataSourceDelegate и UISearchBarDelegate в контроллере представления.
  2. Создайте экземпляр GMSAutocompleteTableDataSource и назначьте контроллер представления в качестве свойства делегата.
  3. Установите свойство GMSAutocompleteTableDataSource в качестве источника данных и свойства делегата экземпляра UITableView в контроллере представления.
  4. В обработчике текстового поля поиска вызовите sourceTextHasChanged для объекта GMSAutocompleteTableDataSource .
    1. Обработайте выбор пользователя в методе делегата didAutocompleteWithPlace .
  5. Закройте контроллер в методах делегата didAutocompleteWithPlace , didFailAutocompleteWithError , wasCancelled .

В следующем примере кода показано, как использовать класс GMSAutocompleteTableDataSource для управления табличным представлением UIViewController , когда UISearchBar добавлен отдельно.

Быстрый

// Copyright 2020 Google LLC
//
// 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 GooglePlaces
import UIKit

class PlaceAutocompleteViewController: UIViewController {

  private var tableView: UITableView!
  private var tableDataSource: GMSAutocompleteTableDataSource!

  override func viewDidLoad() {
    super.viewDidLoad()

    let searchBar = UISearchBar(frame: CGRect(x: 0, y: 20, width: self.view.frame.size.width, height: 44.0))
    searchBar.delegate = self
    view.addSubview(searchBar)

    tableDataSource = GMSAutocompleteTableDataSource()
    tableDataSource.delegate = self

    tableView = UITableView(frame: CGRect(x: 0, y: 64, width: self.view.frame.size.width, height: self.view.frame.size.height - 44))
    tableView.delegate = tableDataSource
    tableView.dataSource = tableDataSource

    view.addSubview(tableView)
  }
}

extension PlaceAutocompleteViewController: UISearchBarDelegate {
  func searchBar(_ searchBar: UISearchBar, textDidChange searchText: String) {
    // Update the GMSAutocompleteTableDataSource with the search text.
    tableDataSource.sourceTextHasChanged(searchText)
  }
}

extension PlaceAutocompleteViewController: GMSAutocompleteTableDataSourceDelegate {
  func didUpdateAutocompletePredictions(for tableDataSource: GMSAutocompleteTableDataSource) {
    // Turn the network activity indicator off.
    UIApplication.shared.isNetworkActivityIndicatorVisible = false
    // Reload table data.
    tableView.reloadData()
  }

  func didRequestAutocompletePredictions(for tableDataSource: GMSAutocompleteTableDataSource) {
    // Turn the network activity indicator on.
    UIApplication.shared.isNetworkActivityIndicatorVisible = true
    // Reload table data.
    tableView.reloadData()
  }

  func tableDataSource(_ tableDataSource: GMSAutocompleteTableDataSource, didAutocompleteWith place: GMSPlace) {
    // Do something with the selected place.
    print("Place name: \(place.name)")
    print("Place address: \(place.formattedAddress)")
    print("Place attributions: \(place.attributions)")
  }

  func tableDataSource(_ tableDataSource: GMSAutocompleteTableDataSource, didFailAutocompleteWithError error: Error) {
    // Handle the error.
    print("Error: \(error.localizedDescription)")
  }

  func tableDataSource(_ tableDataSource: GMSAutocompleteTableDataSource, didSelect prediction: GMSAutocompletePrediction) -> Bool {
    return true
  }
}

      

Objective-C

// Copyright 2020 Google LLC
//
// 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 "PlaceAutocompleteViewController.h"
@import GooglePlaces;
@import UIKit;

@interface PlaceAutocompleteViewController () <GMSAutocompleteTableDataSourceDelegate, UISearchBarDelegate>

@end

@implementation PlaceAutocompleteViewController {
  UITableView *tableView;
  GMSAutocompleteTableDataSource *tableDataSource;
}

- (void)viewDidLoad {
  [super viewDidLoad];

  UISearchBar *searchBar = [[UISearchBar alloc] initWithFrame:CGRectMake(0, 20, self.view.frame.size.width, 44)];
  searchBar.delegate = self;

  [self.view addSubview:searchBar];

  tableDataSource = [[GMSAutocompleteTableDataSource alloc] init];
  tableDataSource.delegate = self;

  tableView = [[UITableView alloc] initWithFrame:CGRectMake(0, 64, self.view.frame.size.width, self.view.frame.size.height - 44)];
  tableView.delegate = tableDataSource;
  tableView.dataSource = tableDataSource;

  [self.view addSubview:tableView];
}

#pragma mark - GMSAutocompleteTableDataSourceDelegate

- (void)didUpdateAutocompletePredictionsForTableDataSource:(GMSAutocompleteTableDataSource *)tableDataSource {
  // Turn the network activity indicator off.
  UIApplication.sharedApplication.networkActivityIndicatorVisible = NO;

  // Reload table data.
  [tableView reloadData];
}

- (void)didRequestAutocompletePredictionsForTableDataSource:(GMSAutocompleteTableDataSource *)tableDataSource {
  // Turn the network activity indicator on.
  UIApplication.sharedApplication.networkActivityIndicatorVisible = YES;

  // Reload table data.
  [tableView reloadData];
}

- (void)tableDataSource:(GMSAutocompleteTableDataSource *)tableDataSource didAutocompleteWithPlace:(GMSPlace *)place {
  // Do something with the selected place.
  NSLog(@"Place name: %@", place.name);
  NSLog(@"Place address: %@", place.formattedAddress);
  NSLog(@"Place attributions: %@", place.attributions);
}

- (void)tableDataSource:(GMSAutocompleteTableDataSource *)tableDataSource didFailAutocompleteWithError:(NSError *)error {
  // Handle the error
  NSLog(@"Error %@", error.description);
}

- (BOOL)tableDataSource:(GMSAutocompleteTableDataSource *)tableDataSource didSelectPrediction:(GMSAutocompletePrediction *)prediction {
  return YES;
}

#pragma mark - UISearchBarDelegate

- (void)searchBar:(UISearchBar *)searchBar textDidChange:(NSString *)searchText {
  // Update the GMSAutocompleteTableDataSource with the search text.
  [tableDataSource sourceTextHasChanged:searchText];
}

@end

      

Настройка цветов текста и фона.

You can set the colors of all text and backgrounds in the autocomplete UI control, to make the widget match the visual appearance of your app more closely. There are two ways to set the UI control colors:

  • Используя встроенный протокол iOS UIAppearance, можно глобально стилизовать элементы управления пользовательского интерфейса, где это возможно. Эти настройки применяются ко многим, но не ко всем элементам управления пользовательского интерфейса.
  • Используя методы SDK в классах виджетов, можно устанавливать свойства, которые не поддерживаются протоколом UIAppearance .

Как правило, ваше приложение будет использовать некоторую комбинацию протокола UIAppearance и методов SDK. На следующей диаграмме показано, какие элементы можно стилизовать:

Цвета элементов управления автозаполнения пользовательского интерфейса

В таблице ниже перечислены все элементы пользовательского интерфейса и указано, как следует стилизовать каждый из них (протокол UIAppearance или метод SDK).

Элемент пользовательского интерфейса Метод Как создать стиль
Оттенок панели навигации (фон) протокол UIAppearance Вызовите setBarTintColor для прокси-объекта UINavigationBar .
Цвет навигационной панели (стрелка в строке поиска и кнопка «Отмена») протокол UIAppearance Вызовите setTintColor для прокси-объекта UINavigationBar .
Цвет текста строки поиска протокол UIAppearance Установите значение NSForegroundColorAttributeName в searchBarTextAttributes .
цвет подсветки поисковой строки Н/Д Поисковая строка полупрозрачна и будет отображаться как затененная версия панели навигации.
Цвет текста-заполнителя в строке поиска (текст поиска по умолчанию) протокол UIAppearance Установите NSForegroundColorAttributeName в placeholderAttributes .
Основной текст (также применяется к тексту ошибок и сообщениям) метод SDK Вызовите функцию primaryTextColor .
Выделение основного текста метод SDK Вызовите функцию primaryTextHighlightColor .
Вторичный текст метод SDK Вызовите функцию secondaryTextColor .
Текст ошибки и сообщения метод SDK Вызовите функцию primaryTextColor .
Фон ячейки таблицы метод SDK Вызовите функцию tableCellBackgroundColor .
Цвет разделителя ячеек таблицы метод SDK Вызовите метод tableCellSeparatorColor .
Кнопка «Попробовать снова» метод SDK Вызовите функцию tintColor .
Индикатор активности (вращающийся индикатор прогресса) протокол UIAppearance Вызовите setColor для прокси-объекта UIActivityIndicatorView .
Логотип «Powered by Google», изображение грустного облака Н/Д Белый или серый вариант автоматически выбирается в зависимости от контраста фона.
Значки лупы и прозрачного текста в текстовом поле строки поиска. Н/Д Для оформления замените изображения по умолчанию изображениями желаемого цвета.

Использование протокола UIAppearance

You can use the UIAppearance protocol to get the appearance proxy for a given UI element, which you can then use to set the color for the UI element. When a modification is made, all instances of a given UI element are affected. For example, the following example globally changes the text color of UITextField classes to green when they are contained in a UISearchBar :

[[UITextField appearanceWhenContainedIn:[UISearchBar class], nil]
    setDefaultTextAttributes:@{NSForegroundColorAttributeName:[UIColor greenColor]}];

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

The following code snippets show all of the proxy commands you need to use to style everything in the full-screen autocomplete UI control. Add this code to the didFinishLaunchingWithOptions method in Appdelegate.m:

// Define some colors.
UIColor *darkGray = [UIColor darkGrayColor];
UIColor *lightGray = [UIColor lightGrayColor];

// Navigation bar background.
[[UINavigationBar appearance] setBarTintColor:darkGray];
[[UINavigationBar appearance] setTintColor:lightGray];

// Color of typed text in the search bar.
NSDictionary *searchBarTextAttributes = @{
                                          NSForegroundColorAttributeName: lightGray,
                                          NSFontAttributeName : [UIFont systemFontOfSize:[UIFont systemFontSize]]
                                          };
[UITextField appearanceWhenContainedInInstancesOfClasses:@[[UISearchBar class]]]
    .defaultTextAttributes = searchBarTextAttributes;

// Color of the placeholder text in the search bar prior to text entry.
NSDictionary *placeholderAttributes = @{
                                        NSForegroundColorAttributeName: lightGray,
                                        NSFontAttributeName : [UIFont systemFontOfSize:[UIFont systemFontSize]]
                                        };

// Color of the default search text.
// NOTE: In a production scenario, "Search" would be a localized string.
NSAttributedString *attributedPlaceholder =
[[NSAttributedString alloc] initWithString:@"Search"
                                attributes:placeholderAttributes];
[UITextField appearanceWhenContainedInInstancesOfClasses:@[[UISearchBar class]]]
    .attributedPlaceholder = attributedPlaceholder;

// Color of the in-progress spinner.
[[UIActivityIndicatorView appearance] setColor:lightGray];

// To style the two image icons in the search bar (the magnifying glass
// icon and the 'clear text' icon), replace them with different images.
[[UISearchBar appearance] setImage:[UIImage imageNamed:@"custom_clear_x_high"]
                  forSearchBarIcon:UISearchBarIconClear
                            state:UIControlStateHighlighted];
[[UISearchBar appearance] setImage:[UIImage imageNamed:@"custom_clear_x"]
                  forSearchBarIcon:UISearchBarIconClear
                            state:UIControlStateNormal];
[[UISearchBar appearance] setImage:[UIImage imageNamed:@"custom_search"]
                    forSearchBarIcon:UISearchBarIconSearch
                            state:UIControlStateNormal];

// Color of selected table cells.
UIView *selectedBackgroundView = [[UIView alloc] init];
selectedBackgroundView.backgroundColor = [UIColor lightGrayColor];
[UITableViewCell appearanceWhenContainedIn:[GMSAutocompleteViewController class], nil]
    .selectedBackgroundView = selectedBackgroundView;

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

A subset of UI control elements have properties that are not affected by the UIAppearance protocol, and so must be set directly. The following code example shows defining foreground and background colors, and applying them to a UI control instance named acController . Add this code to the onLaunchClicked method in ViewController.m:

UIColor *darkGray = [UIColor darkGrayColor];
UIColor *lightGray = [UIColor lightGrayColor];

acController.secondaryTextColor = [UIColor colorWithWhite:1.0f alpha:0.5f];
acController.primaryTextColor = lightGray;
acController.primaryTextHighlightColor = [UIColor grayColor];
acController.tableCellBackgroundColor = darkGray;
acController.tableCellSeparatorColor = lightGray;
acController.tintColor = lightGray;

Получение прогнозов местоположения программным способом

You can create a custom search UI as an alternative to the UI provided by the autocomplete widget. To do this, your app must get place predictions programmatically. Your app can get a list of predicted place names and/or addresses in one of the following ways:

Вызов функции GMSPlacesClient findAutocompletePredictionsFromQuery:

To get a list of predicted place names and/or addresses, first instantiate GMSPlacesClient , then call the GMSPlacesClient findAutocompletePredictionsFromQuery: method with the following parameters:

  • Строка autocompleteQuery содержащая текст, введенный пользователем.
  • A GMSAutocompleteSessionToken , which is used to identify each individual session. Your app should pass the same token for each autocomplete request call, then pass that token, along with a Place ID, in the subsequent call to fetchPlacefromPlaceID: to retrieve Place Details for the place that was selected by the user.
  • Фильтр GMSAutocompleteFilter для:
    • Предвзятость или ограничение результатов определенным регионом.
    • Ограничьте результаты определенным типом мест .
    • Объект GMSPlaceLocationBias /Restriction, изменяющий результаты в сторону определенной области, заданной широтой и долготой.
  • Метод обратного вызова для обработки возвращаемых прогнозов.

Приведенные ниже примеры кода демонстрируют вызов функции findAutocompletePredictionsFromQuery: .

Быстрый

/**
 *   Create a new session token. Be sure to use the same token for calling
 *   findAutocompletePredictions, as well as the subsequent place details request.
 *   This ensures that the user's query and selection are billed as a single session.
 */
let token = GMSAutocompleteSessionToken.init()

// Create a type filter.
let filter = GMSAutocompleteFilter()
filter.types = [kGMSPlaceTypeBank]
filter.locationBias = GMSPlaceRectangularLocationOption( northEastBounds,
                                   southWestBounds);

placesClient?.findAutocompletePredictions(fromQuery: "cheesebu",

                                          filter: filter,
                                          sessionToken: token,
                                          callback: { (results, error) in
    if let error = error {
      print("Autocomplete error: \(error)")
      return
    }
    if let results = results {
      for result in results {
        print("Result \(result.attributedFullText) with placeID \(result.placeID)")
      }
    }
})

Objective-C

/**
 *   Create a new session token. Be sure to use the same token for calling
 *   findAutocompletePredictionsFromQuery:, as well as the subsequent place details request.
 *   This ensures that the user's query and selection are billed as a single session.
 */
GMSAutocompleteSessionToken *token = [[GMSAutocompleteSessionToken alloc] init];

// Create a type filter.
GMSAutocompleteFilter *_filter = [[GMSAutocompleteFilter alloc] init];
_filter.types = @[ kGMSPlaceTypeBank ];

[_placesClient findAutocompletePredictionsFromQuery:@"cheesebu"
filter:_filter sessionToken:token callback:^(NSArray<GMSAutocompletePrediction *> * _Nullable results, NSError * _Nullable error) {
  if (error != nil) {
    NSLog(@"An error occurred %@", [error localizedDescription]);
    return;
  }
  if (results != nil) {
    for (GMSAutocompletePrediction *result in results) {
      NSLog(@"Result %@ with PlaceID %@", result.attributedFullText, result.placeID);
    }
  }
}];

API вызывает указанный метод обратного вызова, передавая в него массив объектов GMSAutocompletePrediction .

Каждый объект GMSAutocompletePrediction содержит следующую информацию:

  • attributedFullText – Полный текст предсказания в виде строки типа NSAttributedString . Например, 'Sydney Opera House, Sydney, New South Wales, Australia'. Каждый текстовый диапазон, соответствующий пользовательскому вводу, имеет атрибут kGMSAutocompleteMatchAttribute . Вы можете использовать этот атрибут для выделения соответствующего текста в запросе пользователя, например, как показано ниже.
  • placeID – Идентификатор предполагаемого места. Place ID – это текстовый идентификатор, который однозначно определяет место. Для получения дополнительной информации об идентификаторах мест см. раздел « Обзор идентификаторов мест» .
  • distanceMeters – Расстояние по прямой от указанной origin до конечной. Если свойство origin не задано, значение distance не будет возвращено.

Следующий пример кода демонстрирует, как выделить жирным шрифтом те части результата, которые соответствуют тексту в запросе пользователя, используя enumerateAttribute :

Быстрый

let regularFont = UIFont.systemFont(ofSize: UIFont.labelFontSize)
let boldFont = UIFont.boldSystemFont(ofSize: UIFont.labelFontSize)

let bolded = prediction.attributedFullText.mutableCopy() as! NSMutableAttributedString
bolded.enumerateAttribute(kGMSAutocompleteMatchAttribute, in: NSMakeRange(0, bolded.length), options: []) {
  (value, range: NSRange, stop: UnsafeMutablePointer<ObjCBool>) -> Void in
    let font = (value == nil) ? regularFont : boldFont
    bolded.addAttribute(NSFontAttributeName, value: font, range: range)
}

label.attributedText = bolded
    

Objective-C

UIFont *regularFont = [UIFont systemFontOfSize:[UIFont labelFontSize]];
UIFont *boldFont = [UIFont boldSystemFontOfSize:[UIFont labelFontSize]];

NSMutableAttributedString *bolded = [prediction.attributedFullText mutableCopy];
[bolded enumerateAttribute:kGMSAutocompleteMatchAttribute
                   inRange:NSMakeRange(0, bolded.length)
                   options:0
                usingBlock:^(id value, NSRange range, BOOL *stop) {
                  UIFont *font = (value == nil) ? regularFont : boldFont;
                  [bolded addAttribute:NSFontAttributeName value:font range:range];
                }];

label.attributedText = bolded;
    

Использование дочернего устройства

If you want to build your own autocomplete control from scratch, you can use GMSAutocompleteFetcher , which wraps the autocompleteQuery method on GMSPlacesClient . The fetcher throttles requests, returning only results for the most recently entered search text. It provides no UI elements.

Для реализации GMSAutocompleteFetcher выполните следующие шаги:

  1. Реализуйте протокол GMSAutocompleteFetcherDelegate .
  2. Создайте объект GMSAutocompleteFetcher .
  3. Вызывайте sourceTextHasChanged в обработчике текста по мере ввода пользователем данных.
  4. Обрабатывайте прогнозы и ошибки, используя методы протокола didAutcompleteWithPredictions и didFailAutocompleteWithError .

The following code example demonstrates using the fetcher to take user input and display place matches in a text view. Functionality for selecting a place has been omitted. FetcherSampleViewController derives from UIViewController in FetcherSampleViewController.h.

Быстрый

import UIKit
import GooglePlaces

class ViewController: UIViewController {

  var textField: UITextField?
  var resultText: UITextView?
  var fetcher: GMSAutocompleteFetcher?

  override func viewDidLoad() {
    super.viewDidLoad()

    view.backgroundColor = .white
    edgesForExtendedLayout = []

    // Set bounds to inner-west Sydney Australia.
    let neBoundsCorner = CLLocationCoordinate2D(latitude: -33.843366,
                                                longitude: 151.134002)
    let swBoundsCorner = CLLocationCoordinate2D(latitude: -33.875725,
                                                longitude: 151.200349)

    // Set up the autocomplete filter.
    let filter = GMSAutocompleteFilter()
    filter.locationRestriction = GMSPlaceRectangularLocationOption(neBoundsCorner, swBoundsCorner)

    // Create a new session token.
    let token: GMSAutocompleteSessionToken = GMSAutocompleteSessionToken.init()

    // Create the fetcher.
    fetcher = GMSAutocompleteFetcher(bounds: nil, filter: filter)
    fetcher?.delegate = self
    fetcher?.provide(token)

    textField = UITextField(frame: CGRect(x: 5.0, y: 10.0,
                                          width: view.bounds.size.width - 5.0,
                                          height: 64.0))
    textField?.autoresizingMask = .flexibleWidth
    textField?.addTarget(self, action: #selector(textFieldDidChange(textField:)),
                         for: .editingChanged)
    let placeholder = NSAttributedString(string: "Type a query...")

    textField?.attributedPlaceholder = placeholder

    resultText = UITextView(frame: CGRect(x: 0, y: 65.0,
                                          width: view.bounds.size.width,
                                          height: view.bounds.size.height - 65.0))
    resultText?.backgroundColor = UIColor(white: 0.95, alpha: 1.0)
    resultText?.text = "No Results"
    resultText?.isEditable = false

    self.view.addSubview(textField!)
    self.view.addSubview(resultText!)
  }

  @objc func textFieldDidChange(textField: UITextField) {
    fetcher?.sourceTextHasChanged(textField.text!)
  }

}

extension ViewController: GMSAutocompleteFetcherDelegate {
  func didAutocomplete(with predictions: [GMSAutocompletePrediction]) {
    let resultsStr = NSMutableString()
    for prediction in predictions {
      resultsStr.appendFormat("\n Primary text: %@\n", prediction.attributedPrimaryText)
      resultsStr.appendFormat("Place ID: %@\n", prediction.placeID)
    }

    resultText?.text = resultsStr as String
  }

  func didFailAutocompleteWithError(_ error: Error) {
    resultText?.text = error.localizedDescription
  }
}

Objective-C

#import "FetcherSampleViewController.h"
#import <GooglePlaces/GooglePlaces.h>

@interface FetcherSampleViewController () <GMSAutocompleteFetcherDelegate>

@end

@implementation FetcherSampleViewController {
  UITextField *_textField;
  UITextView *_resultText;
  GMSAutocompleteFetcher* _fetcher;
}

-   (void)viewDidLoad {
  [super viewDidLoad];

  self.view.backgroundColor = [UIColor whiteColor];
  self.edgesForExtendedLayout = UIRectEdgeNone;

  // Set bounds to inner-west Sydney Australia.
  CLLocationCoordinate2D neBoundsCorner = CLLocationCoordinate2DMake(-33.843366, 151.134002);
  CLLocationCoordinate2D swBoundsCorner = CLLocationCoordinate2DMake(-33.875725, 151.200349);

  GMSAutocompleteFilter *autocompleteFilter = [[GMSAutocompleteFilter alloc] init];
  autocompleteFilter.locationRestriction =
        GMSPlaceRectangularLocationOption(neBoundsCorner, swBoundsCorner);

  // Create the fetcher.
  _fetcher = [[GMSAutocompleteFetcher alloc] initWithBounds:nil
                                                     filter:filter];
  _fetcher.delegate = self;

  // Set up the UITextField and UITextView.
  _textField = [[UITextField alloc] initWithFrame:CGRectMake(5.0f,
                                                             0,
                                                             self.view.bounds.size.width - 5.0f,
                                                             44.0f)];
  _textField.autoresizingMask = UIViewAutoresizingFlexibleWidth;
  [_textField addTarget:self
                 action:@selector(textFieldDidChange:)
       forControlEvents:UIControlEventEditingChanged];
  _resultText =[[UITextView alloc] initWithFrame:CGRectMake(0,
                                                            45.0f,
                                                            self.view.bounds.size.width,
                                                            self.view.bounds.size.height - 45.0f)];
  _resultText.backgroundColor = [UIColor colorWithWhite:0.95f alpha:1.0f];
  _resultText.text = @"No Results";
  _resultText.editable = NO;
  [self.view addSubview:_textField];
  [self.view addSubview:_resultText];
}

-   (void)textFieldDidChange:(UITextField *)textField {
  NSLog(@"%@", textField.text);
  [_fetcher sourceTextHasChanged:textField.text];
}

#pragma mark - GMSAutocompleteFetcherDelegate
-   (void)didAutocompleteWithPredictions:(NSArray *)predictions {
  NSMutableString *resultsStr = [NSMutableString string];
  for (GMSAutocompletePrediction *prediction in predictions) {
      [resultsStr appendFormat:@"%@\n", [prediction.attributedPrimaryText string]];
  }
  _resultText.text = resultsStr;
}

-   (void)didFailAutocompleteWithError:(NSError *)error {
  _resultText.text = [NSString stringWithFormat:@"%@", error.localizedDescription];
}

@end

Токены сессии

Токены сессии объединяют этапы запроса и выбора в поиске с автозаполнением в отдельную сессию для целей выставления счетов. Сессия начинается, когда пользователь начинает вводить запрос, и заканчивается, когда он выбирает место. Каждая сессия может содержать несколько запросов, за которыми следует один выбор места. После завершения сессии токен становится недействительным; ваше приложение должно генерировать новый токен для каждой сессии. Мы рекомендуем использовать токены сессии для всех программных сессий автозаполнения (при использовании контроллера полноэкранного режима или контроллера результатов API автоматически позаботится об этом).

The Places SDK for iOS uses a GMSAutocompleteSessionToken to identify each session. Your app should pass a new session token upon beginning each new session, then pass that same token, along with a Place ID, in the subsequent call to fetchPlacefromPlaceID: to retrieve Place Details for the place that was selected by the user.

Узнайте больше о токенах сессии .

Используйте следующий код для генерации нового токена сессии:

let token: GMSAutocompleteSessionToken = GMSAutocompleteSessionToken.init()

Ограничения на использование

Отображение атрибуции в вашем приложении

  • Если ваше приложение использует сервис автозаполнения программным способом, ваш пользовательский интерфейс должен либо отображать ссылку «Powered by Google», либо отображаться на карте с логотипом Google.
  • Если ваше приложение использует элемент управления автозаполнением, никаких дополнительных действий не требуется (необходимая информация об авторстве отображается по умолчанию).
  • Если вы получаете и отображаете дополнительную информацию о месте после определения его по идентификатору , вам также необходимо отображать информацию, предоставленную третьими сторонами.

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

Контроль индикатора сетевой активности

To control the network activity indicator in the applications status bar you must implement the appropriate optional delegate methods for the autocomplete class you are using and turn the network indicator on and off yourself.

  • Для GMSAutocompleteViewController необходимо реализовать методы делегата didRequestAutocompletePredictions: и didUpdateAutocompletePredictions: .
  • For GMSAutocompleteResultsViewController you must implement the delegate methods didRequestAutocompletePredictionsForResultsController: and didUpdateAutocompletePredictionsForResultsController: .
  • Для GMSAutocompleteTableDataSource необходимо реализовать методы делегата didRequestAutocompletePredictionsForTableDataSource: и didUpdateAutocompletePredictionsForTableDataSource: .

Внедрение этих методов и установка параметра [UIApplication sharedApplication].networkActivityIndicatorVisible в значения YES и NO соответственно позволит корректно отображать строку состояния в интерфейсе автозаполнения.

Ограничить результаты автозаполнения

You can set the autocomplete UI control to constrain results to a specific geographic region, and/or filter the results to one or more place types, or to a specific country or countries. To constrain results, you can do the following:

  • To prefer (bias) results within the defined region, set locationBias on the GMSAutocompleteFilter (some results from outside the defined region may still be returned). If locationRestriction is also set, locationBias will be ignored.
  • Чтобы отображать (ограничивать) результаты только в пределах заданного региона, установите locationRestriction для GMSAutocompleteFilter (будут возвращаться только результаты в пределах заданного региона).

    • Примечание: это ограничение применяется только ко всем маршрутам целиком; синтетические результаты, расположенные за пределами прямоугольных границ, могут быть получены на основе маршрута, который перекрывается с ограничением по местоположению.
  • To return only results that conform to a particular place type, set types on the GMSAutocompleteFilter , (for example, specifying kGMSPlaceTypeCollectionAddress will cause the widget to return only results with a precise address).

  • Чтобы отображались результаты только из пяти указанных стран, задайте countries в параметре GMSAutocompleteFilter .

Результаты, искаженные из-за предвзятости в отношении конкретного региона.

Чтобы отдавать предпочтение (смещать) результатам в пределах заданного региона, установите locationBias в параметре GMSAutocompleteFilter , как показано здесь:

northEast = CLLocationCoordinate2DMake(39.0, -95.0);  southWest =
CLLocationCoordinate2DMake(37.5, -100.0);  GMSAutocompleteFilter *filter =
[[GMSAutocompleteFilter alloc] init];  filter.locationBias =
GMSPlaceRectangularLocationOption(northEast, southWest);

Ограничить результаты определенным регионом

Чтобы отображать (ограничивать) результаты только в пределах заданного региона, установите locationRestriction для GMSAutocompleteFilter , как показано здесь:

northEast = CLLocationCoordinate2DMake(39.0, -95.0);  southWest =
CLLocationCoordinate2DMake(37.5, -100.0);  GMSAutocompleteFilter *filter =
[[GMSAutocompleteFilter alloc] init];  filter.locationRestriction =
GMSPlaceRectangularLocationOption(northEast, southWest);

Фильтрация результатов по стране

Чтобы отфильтровать результаты в пределах пяти указанных стран, задайте countries в параметре GMSAutocompleteFilter , как показано здесь:

GMSAutocompleteFilter *filter = [[GMSAutocompleteFilter alloc] init];
filter.countries = @[ @"au", @"nz" ];

Фильтрация результатов по типу места или типу коллекции

Restrict results to be of a certain type or type collection by setting the types property of GMSAutoCompleteFilter . Use this property to specify filters listed in Tables 1, 2, and 3 on Place Types . If nothing is specified, all types are returned.

Чтобы указать фильтр по типу или коллекции типов:

  • С помощью свойства types можно указать до пяти значений типа из таблиц 1 и 2, представленных в разделе «Типы мест» . Значения типа определяются константами в GMSPlaceType .

  • Свойство types позволяет указать набор типов из таблицы 3, представленной в разделе «Типы мест» . Значения набора типов определяются константами в GMSPlaceType .

    В запросе допускается указание только одного типа из Таблицы 3. Если вы указываете значение из Таблицы 3, вы не можете указать значение из Таблицы 1 или Таблицы 2. В противном случае возникнет ошибка.

For example, to return only results that conform to a particular place type, set types on the GMSAutocompleteFilter . The following example shows setting the filter to return only results with a precise address:

GMSAutocompleteFilter *filter = [[GMSAutocompleteFilter alloc] init];
filter.types = @[ kGMSPlaceTypeAirport, kGMSPlaceTypeAmusementPark ];

Оптимизация автозаполнения (устаревшая функция)

В этом разделе описаны лучшие практики, которые помогут вам максимально эффективно использовать сервис автозаполнения мест (устаревшая версия).

Вот несколько общих рекомендаций:

Передовые методы оптимизации затрат

Базовая оптимизация затрат

To optimize the cost of using the Place Autocomplete (Legacy) service, use field masks in Place Details (Legacy) and Place Autocomplete (Legacy) widgets to return only the Place Autocomplete (Legacy) data fields you need.

Расширенная оптимизация затрат

Рассмотрите возможность программной реализации функции автозаполнения мест (устаревшая версия), чтобы получить доступ к ценообразованию SKU: Автозаполнение — за запрос и запрашивать результаты API геокодирования для выбранного места вместо подробных сведений о месте (устаревшая версия). Ценообразование за запрос в сочетании с API геокодирования более экономически выгодно, чем ценообразование за сессию (на основе сессии), если выполняются оба следующих условия:

  • Если вам нужны только широта/долгота или адрес выбранного пользователем места, API геокодирования предоставит эту информацию дешевле, чем вызов функции «Подробная информация о месте» (устаревшая версия).
  • If users select an autocomplete prediction within an average of four Place Autocomplete (Legacy) predictions requests or fewer, per-request pricing may be more cost-effective than per-session pricing.
For help selecting the Place Autocomplete (Legacy) implementation that fits your needs, select the tab that corresponds to your answer to the following question.

Does your application require any information other than the address and latitude/longitude of the selected prediction?

Да, требуется более подробная информация.

Используйте функцию автозаполнения мест на основе сессий (устаревшая версия) с подробным описанием мест (устаревшая версия).
Since your application requires Place Details (Legacy), such as the place name, business status, or opening hours, your implementation of Place Autocomplete (Legacy) should use a session token ( programmatically or built into the JavaScript , Android , or iOS widgets) per session plus applicable Places Data SKUs , depending on which place data fields you request. 1

Реализация виджета
Управление сессиями автоматически встраивается в виджеты JavaScript , Android или iOS . Это включает в себя как запросы автозаполнения (устаревшая версия), так и запросы сведений о выбранном прогнозе (устаревшая версия). Обязательно укажите параметр fields , чтобы гарантировать, что вы запрашиваете только необходимые поля данных для автозаполнения (устаревшая версия).

Программная реализация
Use a session token with your Place Autocomplete (Legacy) requests. When requesting Place Details (Legacy) about the selected prediction, include the following parameters:

  1. The place ID from the Place Autocomplete (Legacy) response
  2. The session token used in the Place Autocomplete (Legacy) request
  3. The fields parameter specifying the Place Autocomplete (Legacy) data fields you need

Нет, достаточно указать адрес и местоположение.

API геокодирования может оказаться более экономически выгодным вариантом, чем Place Details (устаревшая версия), для вашего приложения, в зависимости от производительности функции автозаполнения Place Autocomplete (устаревшая версия). Эффективность функции автозаполнения Place Autocomplete (устаревшая версия) в каждом приложении варьируется в зависимости от того, что вводят пользователи, где используется приложение и были ли внедрены лучшие практики оптимизации производительности .

In order to answer the following question, analyze how many characters a user types on average before selecting a Place Autocomplete (Legacy) prediction in your application.

Do your users select a Place Autocomplete (Legacy) prediction in four or fewer requests, on average?

Да

Implement Place Autocomplete (Legacy) programmatically without session tokens and call Geocoding API on the selected place prediction.
API геокодирования предоставляет адреса и координаты широты/долготы. Выполнение четырех запросов автозаполнения за запрос плюс вызов API геокодирования для прогнозирования выбранного места обходится дешевле, чем стоимость автозаполнения мест (устаревшая версия) за сессию. 1

Consider employing performance best practices to help your users get the prediction they're looking for in even fewer characters.

Нет

Use session-based Place Autocomplete (Legacy) with Place Details (Legacy).
Поскольку среднее количество запросов, которые, как ожидается, будут отправлены до того, как пользователь выберет вариант автозаполнения места (устаревшая версия), превышает стоимость за сессию, ваша реализация автозаполнения места (устаревшая версия) должна использовать токен сессии как для запросов автозаполнения места (устаревшая версия), так и для связанного с ними запроса сведений о месте (устаревшая версия) за сессию . 1

Реализация виджета
Управление сессиями автоматически встраивается в виджеты JavaScript , Android или iOS . Это включает в себя как запросы автозаполнения (устаревшая версия), так и запросы сведений (устаревшая версия) для выбранного прогноза. Обязательно укажите параметр fields , чтобы гарантировать запрос только необходимых полей.

Программная реализация
Use a session token with your Place Autocomplete (Legacy) requests. When requesting Place Details (Legacy) about the selected prediction, include the following parameters:

  1. The place ID from the Place Autocomplete (Legacy) response
  2. The session token used in the Place Autocomplete (Legacy) request
  3. The fields parameter specifying Basic Data fields such as address and geometry

Consider delaying Place Autocomplete (Legacy) requests
Вы можете использовать такие стратегии, как задержка запроса автозаполнения места (Legacy) до тех пор, пока пользователь не введёт первые три или четыре символа, чтобы ваше приложение выполняло меньше запросов. Например, если отправлять запросы автозаполнения места (Legacy) для каждого символа после того, как пользователь введёт третий символ, это означает, что если пользователь введёт семь символов, а затем выберет предсказание, для которого вы отправите один запрос API геокодирования, общая стоимость составит 4 запроса автозаполнения места (Legacy) + геокодирование. 1

Если задержка запросов позволяет снизить среднее количество программных запросов до менее чем четырех, вы можете следовать рекомендациям по эффективной реализации автозаполнения мест (устаревшая версия) с использованием API геокодирования . Обратите внимание, что задержка запросов может восприниматься пользователем как задержка, поскольку он может ожидать увидеть подсказки при каждом новом нажатии клавиши.

Consider employing performance best practices to help your users get the prediction they're looking for in fewer characters.

лучшие практики повышения производительности

The following guidelines describe ways to optimize Place Autocomplete (Legacy) performance:

  • Добавьте в свою реализацию функции автозаполнения мест (устаревшая версия) ограничения по странам, учет местоположения и (для программных реализаций) предпочтения языка. Предпочтения языка не требуются для виджетов, поскольку они получают информацию о языке из браузера или мобильного устройства пользователя.
  • If Place Autocomplete (Legacy) is accompanied by a map, you can bias location by map viewport.
  • В ситуациях, когда пользователь не выбирает один из вариантов автозаполнения поля "Расположение" (устаревшая версия), как правило, потому что ни один из этих вариантов не соответствует желаемому адресу, вы можете повторно использовать исходный ввод пользователя, чтобы попытаться получить более релевантные результаты:
    • If you expect the user to enter only address information, reuse the original user input in a call to the Geocoding API .
    • Если вы ожидаете, что пользователь будет вводить запросы для конкретного места по названию или адресу, используйте запрос «Подробная информация о месте (устаревшая версия)». Если результаты ожидаются только в определенном регионе, используйте предвзятость по местоположению .
    Other scenarios when it's best to fall back to the Geocoding API include:
    • Пользователи вводят адреса подобъектов, например, адреса конкретных квартир или апартаментов в здании. Например, чешский адрес "Stroupežnického 3191/17, Praha" выдает частичное предсказание в функции автозаполнения мест (устаревшая версия).
    • Users inputting addresses with road-segment prefixes like "23-30 29th St, Queens" in New York City or "47-380 Kamehameha Hwy, Kaneohe" on the island of Kauai in Hawai'i.

Смещение в сторону местоположения

Отображение результатов в заданной области осуществляется путем передачи параметра location и параметра radius . Это указывает функции автозаполнения мест (устаревшая версия) отдавать предпочтение отображению результатов в пределах определенной области. Результаты за пределами определенной области также могут отображаться. Вы можете использовать параметр includedRegionCodes для фильтрации результатов, чтобы отображать только места в пределах указанной страны.

Ограничение местоположения

Restrict results to a specified area by passing a locationRestriction parameter.

Вы также можете ограничить результаты областью, определенной параметром location и radius , добавив параметр strictbounds . Это указывает функции автозаполнения мест (устаревшая версия) возвращать только результаты в пределах этой области.

Поиск неисправностей

Хотя могут возникать самые разные ошибки, большинство ошибок, с которыми, скорее всего, столкнется ваше приложение, обычно вызваны ошибками конфигурации (например, был использован неправильный ключ API или ключ API был настроен некорректно) или ошибками квоты (ваше приложение превысило свою квоту). Дополнительную информацию о квотах см. в разделе «Ограничения использования» .

Ошибки, возникающие при использовании элементов управления автозаполнения, возвращаются в методе didFailAutocompleteWithError() различных протоколов делегата. Свойство code предоставленного объекта NSError устанавливается в одно из значений перечисления GMSPlacesErrorCode .