Place Autocomplete

Platform seçin: Android iOS JavaScript Web Hizmeti

iOS için Yerler SDK'sındaki otomatik tamamlama hizmeti, kullanıcı arama sorgularına yanıt olarak tahminde bulunmanızı sağlar. Kullanıcı yazarken otomatik tamamlama hizmeti, şunun gibi yerler için öneriler döndürüyor: adresleri, artı kodlarını ve noktaları anlatacağım.

Otomatik tamamlamayı uygulamanıza aşağıdaki şekillerde ekleyebilirsiniz:

Otomatik tamamlama kullanıcı arayüzü kontrolü ekleme

Otomatik tamamlama kullanıcı arayüzü kontrolü, yerleşik otomatik tamamlama özelliğine sahip bir arama iletişim kutusudur işlevi görür. Kullanıcı arama terimlerini girdiğinde, kontrol paneli tahmin edilen yerlerin listesi. Kullanıcı seçim yaparken, GMSPlace döndürülmesini sağlar. Uygulamanız bu örneği kullanarak seçili yer.

Otomatik tamamlama kullanıcı arayüzü kontrolünü aşağıdaki yöntemlerle uygulamanıza ekleyebilirsiniz:

Tam ekran denetimi ekleme

Kalıcı bağlam istediğinizde tam ekran kontrolünü kullanın. otomatik tamamlama kullanıcı arayüzü, kullanıcı seçimini yaptı. Bu işlev GMSAutocompleteViewController sınıfını kullanır. Kullanıcı bir yer seçtiğinde uygulamanız geri arama alır.

Uygulamanıza tam ekran kontrolü eklemek için:

  1. Otomatik tamamlama kullanıcı arayüzü kontrolünü başlatmak için ana uygulamanızda bir kullanıcı arayüzü öğesi oluşturun. örneğin, UIButton cihazındaki dokunma işleyici.
  2. GMSAutocompleteViewControllerDelegate'nu uygulama ana görünüm denetleyicisidir.
  3. GMSAutocompleteViewController örneği oluşturma ve üst görünüm denetleyicisini delege özelliği olarak atayın.
  4. Bir GMSPlaceField oluşturun döndürülecek yer verisi türlerini tanımlayın.
  5. GMSAutocompleteFilter ekleyin kullanabilirsiniz.
  6. GMSAutocompleteViewController sunun. [self presentViewController...] kullanılıyor.
  7. didAutocompleteWithPlace içinde kullanıcının seçimini işleyin delege yöntemidir.
  8. didAutocompleteWithPlace içinde kumandayı kapatabilirsiniz, didFailAutocompleteWithError ve wasCancelled yetki verme yöntemleri.

Aşağıdaki örnekte, reklam yayınlamaya başlamanın GMSAutocompleteViewController bir düğmeye dokunan kullanıcıya yanıt olarak gösterilir.

Swift

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 = [.address]
    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

Sonuç denetleyici ekleme

Metin girişi kullanıcı arayüzü üzerinde daha fazla kontrol sahibi olmak istediğinizde sonuç denetleyicisi kullanın. Sonuç denetleyici, sonuç listesinin görünürlüğünü dinamik olarak değiştirir kullanıcı arayüzü odağına göre.

Uygulamanıza sonuç denetleyici eklemek için:

  1. Bir GMSAutocompleteResultsViewController oluşturun.
  2. GMSAutocompleteResultsViewControllerDelegate'nu uygulama protokolüne eklemeli ve üst görünüm denetleyicisini delege özelliği.
  3. Şunu ileterek bir UISearchController nesnesi oluşturun: GMSAutocompleteResultsViewController ifadesini kullanın.
  4. GMSAutocompleteResultsViewController ayarını yapın. olarak, UISearchController öğesinin searchResultsUpdater özelliği olarak kullanılır.
  5. UISearchController için searchBar bilgisini uygulamanızın kullanıcı arayüzüne ekleyin.
  6. didAutocompleteWithPlace içinde kullanıcının seçimini işleyin delege yöntemidir.

UISearchController arama çubuğunu Uygulamanızın kullanıcı arayüzü:

Gezinme çubuğuna arama çubuğu ekleme

Aşağıdaki kod örneğinde, searchBar ekleme ve kullanıcının seçimini işleme:

Swift

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;
}

Bir görünümün üst kısmına arama çubuğu ekleme

Aşağıdaki kod örneğinde, searchBar öğesinin bir görünümün üst kısmına eklenmesi gösterilmektedir.

Swift

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;
}

Varsayılan olarak UISearchController Sunum yapılırken gezinme çubuğunu gizler (bu özellik devre dışı bırakılabilir). Bazı durumlarda gezinme çubuğu görünür ve opak, UISearchController ayarlanmamış doğru şekilde yerleştirin.

Geçici bir çözüm olarak aşağıdaki kodu kullanın:

Swift

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;

Pop-up sonuçlarını kullanarak arama çubuğu ekleme

Aşağıdaki kod örneğinde, arama kutusunun sağ tarafına bir arama çubuğu gezinme çubuğunu ve sonuçların bir pop-up penceresinde görüntülenmesini sağlayabilirsiniz.

Swift

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;
}

Tablo veri kaynağı kullanma

Uygulamanızın özel bir arama metni kullanıcı arayüzü varsa GMSAutocompleteTableDataSource sınıfını kullanın.

GMSAutocompleteTableDataSource uygulamasını kullanmak için UITableViewnın veri kaynağı ve yetkisi olan görüntüleme denetleyicisinde:

  1. GMSAutocompleteTableDataSourceDelegate'nu uygulama ve UISearchBarDelegate protokolleri ekleyebilirsiniz.
  2. Bir GMSAutocompleteTableDataSource oluşturun örneği oluşturun ve görünüm denetleyicisini delege özelliği olarak atayın.
  3. GMSAutocompleteTableDataSource ayarını yapın. Bu, UITableView için veri kaynağı ve yetki mülkleri olarak izleme denetleyicisinde yer alır.
  4. Arama metni girişi işleyicisinde, sourceTextHasChanged GMSAutocompleteTableDataSource
  5. didAutocompleteWithPlace yetki verme yönteminde kullanıcı seçimini yönetin.
  6. didAutocompleteWithPlace, didFailAutocompleteWithError ve sonraki bölümlerde kumandayı kapatabilirsiniz. wasCancelled delege yöntemi.

Aşağıdaki kod örneğinde, GMSAutocompleteTableDataSource sınıfını kullanın.UIViewControllerUISearchBar

Swift

// 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

      

Metin ve arka plan renklerini özelleştirme

Otomatik tamamlama kullanıcı arayüzünde tüm metin ve arka planların renklerini ayarlayabilirsiniz widget'ı, uygulamanızın görsel görünümüne daha uygun hale getirmek için yakından inceleyeceğiz. Kullanıcı arayüzü kontrol renklerini ayarlamanın iki yolu vardır:

  • Mümkün olduğunda kullanıcı arayüzü kontrollerinin genel stilini belirlemek için yerel iOS UIViewance protokolünü kullanarak. Bu ayarlar, tüm kullanıcı arayüzü denetimlerinde değil, öğeler.
  • Widget sınıflarındaki SDK yöntemlerini kullanarak UIViewance protokolü tarafından desteklenmez.

Uygulamanız genellikle UIGörünüm protokolünün bir kombinasyonunu kullanır ve SDK yöntemleri. Aşağıdaki şemada, hangi öğelere stil eklenebileceği gösterilmektedir:

Otomatik tamamlama kullanıcı arayüzü kontrol renkleri

Aşağıdaki tabloda, tüm UI öğeleri listelenmekte ve her bir öğenin bir stil belirlenmelidir (UIViewance protokolü veya SDK yöntemi).

Kullanıcı Arayüzü Öğesi Yöntem Moda bilgileri
Gezinme çubuğu tonu (arka plan) UIGörünüm protokolü UINavigationBar proxy'sinde setBarTintColor öğesini çağır.
Gezinme Çubuğu ton rengi (arama çubuğu metin imleci ve İptal düğmesi) UIGörünüm protokolü UINavigationBar proxy'sinde setTintColor öğesini çağır.
Arama Çubuğu metin rengi UIGörünüm protokolü searchBarTextAttributes içinde NSForegroundColorAttributeName ayarlayın.
Arama çubuğu ton rengi Yok Arama çubuğu yarı saydamdır ve gölgeli bir sürüm olarak görüntülenir tıklayın.
Arama çubuğu yer tutucu metin rengi (varsayılan arama metni) UIGörünüm protokolü placeholderAttributes içinde NSForegroundColorAttributeName ayarlayın.
Birincil metin (hata ve ileti metnine de uygulanır) SDK yöntemi primaryTextColor Hizmetleri İçin Arayın.
Birincil metin vurgulama SDK yöntemi primaryTextHighlightColor Hizmetleri İçin Arayın.
İkincil metin SDK yöntemi secondaryTextColor Hizmetleri İçin Arayın.
Hata ve mesaj metni SDK yöntemi primaryTextColor Hizmetleri İçin Arayın.
Tablo hücre arka planı SDK yöntemi tableCellBackgroundColor Hizmetleri İçin Arayın.
Tablo hücre ayırıcı rengi SDK yöntemi tableCellSeparatorColor Hizmetleri İçin Arayın.
"Tekrar dene" düğme SDK yöntemi tintColor Hizmetleri İçin Arayın.
Etkinlik göstergesi (ilerleme döner simgesi) UIGörünüm protokolü UIActivityIndicatorView proxy'sinde setColor öğesini çağır.
"Google tarafından desteklenmektedir" logo, Üzgün bulut resmi Yok Arka plan kontrastına göre beyaz veya gri sürüm otomatik olarak seçilir.
Arama Çubuğu metin alanında büyüteç ve temiz metin simgeleri Yok Stil için varsayılan resimleri istediğiniz renkteki resimlerle değiştirin.

UIViewance protokolünü kullanma

UIViewance protokolünü kullanabilirsiniz oluşturmak için kullanabilirsiniz. kullanıcı arayüzü öğesinin rengini ayarlayın. Bir değişiklik yapıldığında, kullanıcı arayüzü öğesinin nasıl etkilendiğini gösterir. Örneğin, aşağıdaki örnek global olarak UITextField sınıfın metin rengini yeşile dönüştürür UISearchBar içerir:

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

Renk değerlerini tanımlama hakkında daha fazla bilgi için şu sayfaya bakın: UIColor Sınıf Referansı.

Aşağıdaki kod snippet'leri, tam ekran otomatik tamamlama kullanıcı arayüzü denetiminde her şeyin stilini ayarlayın. Bu kodu ekleyin Appdelegate.m'deki didFinishLaunchingWithOptions yöntemine:

// 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;

Kullanıcı arayüzü kontrol stili özelliklerini ayarlama

Kullanıcı arayüzü kontrol öğelerinin bir alt kümesi, UIGörünümü protokolünden, bu nedenle doğrudan ayarlanmalıdır. Aşağıdaki kod örneği , ön ve arka plan renklerini tanımlayan ve bunları bir kullanıcı arayüzüne uygulayarak gösteriyor acController adlı kontrol örneği. Bu kodu onLaunchClicked cihazına ekleyin yöntemini ViewController.m'de kullanabilirsiniz:

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;
.

Yer tahminlerini programatik olarak alma

otomatik tamamlama widget'ı. Bunun için uygulamanızın yer tahminleri alması gerekir daha fazla bilgi edindiniz. Uygulamanız, tahmin edilen yer adlarının bir listesini ve/veya aşağıdaki yöntemlerden biriyle gönderebilirsiniz:

GMSPlacesClient findAutocompletePredictionsFromQuery: aranıyor

Tahmini yer adlarının ve/veya adreslerin listesini almak için GMSPlacesClient uygulamasını başlatırsanız ardından, GMSPlacesClient findAutocompletePredictionsFromQuery: yöntemini kullanabilirsiniz:

  • Kullanıcının yazdığı metni içeren autocompleteQuery dizesi.
  • GMSAutocompleteSessionToken, Bu kimlik, her bir oturumu tanımlamak için kullanılır. Uygulamanız her otomatik tamamlama isteği çağrısı için aynı jetonu iletecek, ardından bu jetonu iletecek, fetchPlacefromPlaceID:'e yapılan bir sonraki çağrıda, yer kimliğiyle birlikte simgesini tıklayın.
  • Aşağıdakileri yapmak için GMSAutocompleteFilter:
    • Yanlı olma veya sonuçları belirli bir bölgeyle sınırlandırma.
    • Sonuçları belirli bir yer türüyle sınırlandırın.
    • Sonuçlara enlem ve boylam sınırlarıyla belirtilen belirli bir alana ağırlık veren GMSPlaceLocationBias/Kısıtlama nesnesi.
  • Döndürülen tahminleri işlemek için bir geri çağırma yöntemi.

Aşağıdaki kod örneklerinde bir findAutocompletePredictionsFromQuery: çağrısı gösterilmektedir.

Swift

/**
 * 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 = [.bank] 
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, belirtilen bir geri çağırma yöntemini çağırarak GMSAutocompletePrediction nesneler'i tıklayın.

Her bir GMSAutocompletePrediction nesnesi aşağıdaki bilgileri içerir:

  • attributedFullText – Tahminin tam metni şu biçimdedir: NSAttributedString. Örneğin, "Sidney Opera Binası, Sydney, New South Galler, Avustralya". Kullanıcı girişiyle eşleşen her metin aralığı bir özelliği, kGMSAutocompleteMatchAttribute. Bu özelliği aşağıdaki amaçlarla kullanabilirsiniz: kullanıcının sorgusunda eşleşen metni vurgula (örneğin, aşağıda gösterildiği gibi).
  • placeID: Tahmin edilen yerin yer kimliğidir. Yer kimliği, bir yeri benzersiz şekilde tanımlayan metinsel tanımlayıcıdır. Daha fazla bilgi için Yer kimliğine genel bakış başlıklı makaleyi inceleyin.
  • distanceMeters – Belirtilen noktadan düz çizgiyle uzaklık Hedefe origin. origin özelliği ayarlanmazsa mesafe yok değeri döndürülür.

Aşağıdaki kod örneğinde, farklı kısımlarda kalın metinle kullanıcının sorgusundaki metinle eşleşen sonucun enumerateAttribute kullanılarak oluşturulması:

Swift

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;
    

Alıcıyı kullanma

Kendi otomatik tamamlama denetiminizi sıfırdan oluşturmak istiyorsanız GMSAutocompleteFetcher, GMSPlacesClient üzerinde autocompleteQuery yöntemini sarmalayan. Alıcı, istekleri kısıtlayarak yalnızca en son girilen arama metni. Kullanıcı arayüzü öğeleri sağlamaz.

GMSAutocompleteFetcher'i uygulamak için şu adımları uygulayın:

  1. GMSAutocompleteFetcherDelegate'nu uygulama protokolü.
  2. GMSAutocompleteFetcher nesnesi oluşturun.
  3. Kullanıcı yazarken alıcıda sourceTextHasChanged komutunu çağırın.
  4. Tahminleri ve hataları didAutcompleteWithPredictions kullanarak ele alma ve didFailAutocompleteWithError protokol yöntemleri.

Aşağıdaki kod örneğinde, kullanıcı girişi almak için alıcı özelliğinin kullanımı gösterilmektedir ve yer eşleşmelerini metin görünümünde görüntüleyebilirsiniz. Yer seçme işlevi atlandı. FetcherSampleViewController, UIViewController kaynağından türetilir FetcherSampleViewController.h.

Swift

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>
#import <GoogleMapsBase/GoogleMapsBase.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

Oturum jetonları

Oturum jetonları, kullanıcının otomatik tamamlamasının sorgu ve seçim aşamalarını gruplandırır faturalandırma amacıyla ayrı bir oturumda arama yapabilir. Oturum şu tarihte başlar: Kullanıcı sorgu yazmaya başlar ve yeri seçtiğinde işlemi tamamlar. Her biri oturumda birden fazla sorgu bulunabilir ve ardından tek bir yer seçimi yapılabilir. Bir oturum sona erdi, jeton artık geçerli değil; uygulamanızın yeni bir jeton oluşturulur. Tüm kullanıcılar için oturum jetonları kullanmanızı öneririz: otomatik tamamlama oturumları (tam ekranlı kumandayı kullandığınızda veya sonuç denetleyici, API bunu otomatik olarak halleder).

iOS için Yerler SDK'sı bir GMSAutocompleteSessionToken kullanır tanımlamanız gerekir. Uygulamanız, aşağıdaki durumlarda yeni bir oturum jetonu geçirmelidir: ardından aynı jetonu, yer kimliğiyle birlikte iletecek şekilde ekleyebilirsiniz. fetchPlacefromPlaceID: adresine yapılan sonraki çağrıda simgesini tıklayın.

Oturum jetonları hakkında daha fazla bilgi edinin.

Yeni bir oturum jetonu oluşturmak için aşağıdaki kodu kullanın:

let token: GMSAutocompleteSessionToken = GMSAutocompleteSessionToken.init()

Kullanım sınırları

İlişkilendirmeleri uygulamanızda gösterme

  • Uygulamanız otomatik tamamlama hizmetini programatik olarak kullanıyorsa kullanıcı arayüzünüz "Google tarafından desteklenmektedir" mesajını veya bir Google markalı harita.
  • Uygulamanız otomatik tamamlama kullanıcı arayüzü kontrolünü kullanıyorsa ek bir işlem yapmanız gerekmez (varsayılan olarak gerekli atıf gösterilir).
  • Sonradan ek yer bilgileri alıp görüntülerseniz bir yeri kimliğine göre öğrenmek, üçüncü taraf ilişkilendirmelerini de göstermeniz gerekir.

Daha fazla bilgi için ilişkilendirmeler.

Ağ etkinliği göstergesini denetleme

Uygulamaların durum çubuğundaki ağ etkinliği göstergesini kontrol etmek için otomatik tamamlama için isteğe bağlı uygun yetki verme yöntemlerini uygulamalıdır ağ göstergesini açıp kapatın.

  • GMSAutocompleteViewController için didRequestAutocompletePredictions: ve didUpdateAutocompletePredictions: yetki verme yöntemlerini uygulamanız gerekir.
  • GMSAutocompleteResultsViewController için didRequestAutocompletePredictionsForResultsController: ve didUpdateAutocompletePredictionsForResultsController: yetki verme yöntemlerini uygulamanız gerekir.
  • GMSAutocompleteTableDataSource için didRequestAutocompletePredictionsForTableDataSource: ve didUpdateAutocompletePredictionsForTableDataSource: yetki verme yöntemlerini uygulamanız gerekir.

Bu yöntemleri uygulayıp [UIApplication sharedApplication].networkActivityIndicatorVisible ayarlayarak YES ve NO olarak ayarladığınızda, durum çubuğu otomatik tamamlama kullanıcı arayüzünü açın.

Otomatik tamamlama sonuçlarını sınırla

Otomatik tamamlama kullanıcı arayüzü denetimini, sonuçları belirli bir ve/veya sonuçları bir ya da daha fazla yer türüne göre filtreleyebilirsiniz. ülkeler ya da ülkeler. Sonuçları sınırlandırmak için aşağıdakileri yapabilirsiniz:

  • Tanımlanan bölge dahilindeki sonuçları tercih etmek (önyargı) için şu değeri ayarlayın: locationBias GMSAutocompleteFilter (tanımlanan bölgenin dışından bazı sonuçlar döndürülmesi gerekir). locationRestriction politikası da ayarlanırsa locationBias yoksayılır.
  • Yalnızca tanımlanan bölgedeki sonuçları göstermek (kısıtlamak) için GMSAutocompleteFilter üzerinde locationRestriction (yalnızca işleminin sonucu döndürülür.

    • Not: Bu kısıtlama yalnızca tüm rotalara uygulanır. Sentetik Dikdörtgen sınırların dışında bulunan sonuçlar, rotaya bağlı olarak döndürülebilir bir etiket bulun.
  • Yalnızca belirli bir yer türüne uygun sonuçları döndürmek için types değerini ayarlayın (örneğin, TypeFilter.ADDRESS) değerini girerekGMSAutocompleteFilter ise widget'ın yalnızca tam adresi içeren sonuçları döndürmesine neden olur).

  • Yalnızca en fazla beş ülke içindeki sonuçları döndürmek için GMSAutocompleteFilter üzerinde countries.

Belirli bir bölge için yanlı sonuçlar

Tanımlanan bölge dahilindeki sonuçları tercih etmek (önyargı) için şu değeri ayarlayın: locationBias GMSAutocompleteFilter, burada gösterildiği gibi:

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

Sonuçları belirli bir bölgeyle sınırlandırın

Yalnızca tanımlanan bölgedeki sonuçları göstermek (kısıtlamak) için GMSAutocompleteFilter üzerinde locationRestriction (burada gösterildiği gibi):

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

Sonuçları ülkeye göre filtreleyin

En fazla beş ülkede sonuçları filtrelemek için şurada countries ayarlayın: GMSAutocompleteFilter, burada gösterildiği gibi:

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

Sonuçları yer türüne veya koleksiyon türüne göre filtreleyin

types özelliği GMSAutoCompleteFilter Aşağıdaki tablo 1, 2 ve 3'te listelenen filtreleri belirtmek için bu özelliği kullanın Yer Türleri. Hiçbir şey belirtilmezse tüm türler döndürülür.

Bir tür veya tür koleksiyon filtresi belirtmek için:

  • Tablo 1'den en fazla beş type değeri belirtmek için types özelliğini kullanın. ve Yer Türleri'nde Tablo 2'yi görebilirsiniz. Tür değerleri: GMSPlaceType içindeki sabitlerle tanımlanır.

  • Gösterilen Tablo 3'ten bir tür koleksiyonu belirtmek için types özelliğini kullanın Yer Türleri'ne göz atın. Tür koleksiyonu değerleri, GMSPlaceType'teki sabit değerlerdir.

    İstekte Tablo 3'ten yalnızca bir türe izin verilir. Bir değeri tablo 1 veya Tablo 2'den değer belirtemezsiniz. Eğer kullanırsanız bir hata oluşur.

Örneğin, yalnızca belirli bir yer türüne uygun sonuçları döndürmek için, GMSAutocompleteFilter üzerinde types. Aşağıdaki örnekte, filtre uygulayarak yalnızca kesin adresi içeren sonuçları döndürür:

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

Yer Otomatik Tamamlama optimizasyonu

Bu bölümde Google Ads'den en iyi şekilde yararlanmanıza yardımcı olacak en iyi uygulamalar Otomatik Yer Tamamlama hizmeti.

Bazı genel kurallar şunlardır:

  • Çalışan bir kullanıcı arayüzü geliştirmenin en hızlı yolu Maps JavaScript API Otomatik tamamlama widget'ı, Android için Yerler SDK'sı Otomatik tamamlama widget'ı, veya Yerler SDK'sı Otomatik tamamlama kullanıcı arayüzü kontrolü
  • Temel Yer Otomatik Tamamlama özelliği hakkında bilgi sahibi olun veri alanlarını en baştan iki kez kontrol edin.
  • Konuma ağırlık verme ve konum kısıtlama alanları isteğe bağlıdır, ancak otomatik tamamlama performansı üzerinde önemli bir etkisi vardır.
  • Uygulamanızın sorunsuz şekilde düşmesini sağlamak için hata işlemeyi kullanın bir hata döndürür.
  • Uygulamanızın seçim yapılmadığı durumlarda bunu yaptığından ve kullanıcılara seçeneğini tıklayın.

Maliyet optimizasyonuyla ilgili en iyi uygulamalar

Temel maliyet optimizasyonu

Otomatik Yer Tamamlama özelliğini kullanmanın maliyetini optimize etmek için hizmeti kullanmak için, Yer Ayrıntıları ve Yer Otomatik Tamamlama widget'larındaki alan maskelerini kullanarak yalnızca yer veri alanlarını kullanın.

Gelişmiş maliyet optimizasyonu

İstek Başına fiyatlandırma özelliğine erişmek ve seçilen yer hakkında Yer Ayrıntıları yerine Coğrafi Kodlama API'si sonuçlarını istemek için Otomatik Yer Tamamlama özelliğinin programatik olarak uygulanmasını göz önünde bulundurun. Aşağıdaki koşulların her ikisi de karşılanırsa İstek Başına Fiyatlandırma, Geocoding API ile eşleştirilen Oturum Başına (oturuma dayalı) fiyatlandırmadan daha uygun maliyetlidir:

  • Yalnızca kullanıcının seçtiği yerin enlem/boylam veya adresine ihtiyaç duyarsanız Coğrafi Kodlama API'si bu bilgileri Yer Ayrıntısı çağrısından daha düşük bir ücret karşılığında sunar.
  • Kullanıcılar ortalama dört veya daha az Otomatik Tamamlama tahmin isteği içinde bir otomatik tamamlama tahmini seçerse, İstek Başına fiyatlandırma, Oturum Başına fiyatlandırmadan daha uygun maliyetli olabilir.
İhtiyaçlarınıza uyan Otomatik Yer Tamamlama uygulamasını seçme konusunda yardım için aşağıdaki soruya vereceğiniz yanıta karşılık gelen sekmeyi seçin.

Uygulamanız, seçilen tahminin adresi ve enlem/boylam dışında herhangi bir bilgi gerektiriyor mu?

Evet, daha fazla ayrıntı gerekiyor

Yer Ayrıntıları ile oturuma dayalı Otomatik Yer Tamamlama özelliğini kullanın.
. Uygulamanız; yer adı, işletme durumu veya çalışma saatleri gibi Yer Ayrıntıları gerektirdiğinden, Otomatik Yer Tamamlama uygulamanız programatik olarak veya JavaScript, Android ya da iOS widget'larında yerleşik olarak bulunan bir oturum jetonu kullanmalıdır.Bu kullanım için toplamda 0,017 ABD doları tutarında oturum başına maliyet ve geçerli Yer Verileri SKU'ları kullanılır.

Widget uygulaması
Oturum yönetimi otomatik olarak JavaScript, Android veya iOS widget'larına eklenir. Buna hem otomatik Yer Tamamlama istekleri hem de seçilen tahmindeki Yer Ayrıntısı isteği dahildir. Yalnızca şu istekte bulunduğunuzdan emin olmak için fields parametresini belirttiğinizden emin olun: yer verisi alanlarını girin.

Programatik uygulama
Otomatik Yer Tamamlama isteklerinizde bir oturum jetonu kullanın. Seçilen tahmin hakkında Yer Ayrıntıları isterken aşağıdaki parametreleri ekleyin:

  1. Otomatik Yer Tamamlama yanıtındaki yer kimliği
  2. Otomatik Yer Tamamlama isteğinde kullanılan oturum jetonu
  3. fields parametresi, İhtiyacınız olan yer verisi alanlarını

Hayır, yalnızca adres ve konum gerekiyor

Otomatik Yer Tamamlama kullanımınızın performansına bağlı olarak Coğrafi Kodlama API'sı, uygulamanız için Yer Ayrıntıları'ndan daha uygun maliyetli bir seçenek olabilir. Her uygulamanın Otomatik Tamamlama verimliliği, hangi kullanıcıların giriş yaptığına, uygulamanın nerede kullanıldığına ve performans optimizasyonuyla ilgili en iyi uygulamaların uygulanıp uygulanmadığına bağlı olarak değişiklik gösterir.

Aşağıdaki soruyu yanıtlamak için, bir kullanıcının uygulamanızda Yer Otomatik Tamamlama tahmini seçmeden önce ortalama kaç karakter yazdığını analiz edin.

Kullanıcılarınız ortalama olarak dört veya daha az istekte Yer Otomatik Tamamlama tahminini seçiyor mu?

Evet

Otomatik Yer Tamamlama özelliğini oturum jetonları olmadan programatik olarak uygulayın ve seçilen yer tahmininde Coğrafi Kodlama API'sini çağırın.
. Geocoding API, adresleri ve enlem/boylam koordinatlarını istek başına 0,005 ABD doları karşılığında sunar. Dört adet Otomatik Otomatik Tamamlama - İstek Başına isteği göndermenin maliyeti 0,01132 ABD dolarıdır. Bu nedenle, seçilen yer tahminiyle ilgili dört isteğin toplam maliyeti ve Coğrafi Kodlama API'si çağrısı 0,01632 ABD doları olur. Bu da oturum başına 0,017 ABD doları olan Oturum Başına Otomatik Tamamlama fiyatından daha düşüktür.1

Kullanıcılarınızın aradıkları tahmini daha az karakterle bulmalarına yardımcı olmak için performans en iyi uygulamalarından yararlanmayı düşünebilirsiniz.

Hayır

Yer Ayrıntıları ile oturuma dayalı Otomatik Yer Tamamlama özelliğini kullanın.
. Bir kullanıcı Otomatik Yer Tamamlama tahminini seçmeden önce gerçekleştirmeyi beklediğiniz ortalama istek sayısı Oturum Başına fiyatlandırmayı aştığından, Otomatik Yer Tamamlama özelliğini uygulamanız hem Otomatik Yer Tamamlama istekleri hem de bununla ilişkili Yer Ayrıntısı isteği için bir oturum jetonu kullanarak toplam oturum başına 0,017 ABD doları tutarında maliyet içermelidir.1

Widget uygulaması
Oturum yönetimi otomatik olarak JavaScript, Android veya iOS widget'larına eklenir. Buna hem otomatik Yer Tamamlama istekleri hem de seçilen tahmindeki Yer Ayrıntısı isteği dahildir. Yalnızca Temel Veriler alanlarını istediğinizden emin olmak için fields parametresini belirttiğinizden emin olun.

Programatik uygulama
Otomatik Yer Tamamlama isteklerinizde bir oturum jetonu kullanın. Seçilen tahmin hakkında Yer Ayrıntıları isterken aşağıdaki parametreleri ekleyin:

  1. Otomatik Yer Tamamlama yanıtındaki yer kimliği
  2. Otomatik Yer Tamamlama isteğinde kullanılan oturum jetonu
  3. Adres ve geometri gibi Temel Veri alanlarını belirten fields parametresi

Yer Otomatik Tamamlama isteklerini ertelemeyi düşünün
Otomatik Yer Tamamlama isteğini, kullanıcı ilk üç veya dört karakteri yazana kadar ertelemek gibi stratejiler kullanarak uygulamanızın daha az istek göndermesini sağlayabilirsiniz. Örneğin, kullanıcı üçüncü karakteri yazdıktan sonra her karakter için Otomatik Tamamlama isteklerinde bulunmak, kullanıcı yedi karakteri yazdıktan sonra bir Coğrafi Kodlama API'si isteği gönderdiğiniz bir tahmin seçerse toplam maliyetin 0,01632 ABD doları (4 * 0,00283 ABD doları Otomatik Tamamlama + 0,005 ABD doları Coğrafi Kodlama) olacağı anlamına gelir.1

İstekleri ertelemek ortalama programatik isteğinizin dörtün altına düşmesine neden oluyorsa Geocoding API ile otomatik yer tamamlama performansı uygulama yönergelerinden yararlanabilirsiniz. İsteklerin geciktirilmesinin, her yeni tuş vuruşunda tahmin görmeyi bekleyen kullanıcılar tarafından gecikme olarak algılanabileceğini unutmayın.

Kullanıcılarınızın aradıkları tahmini daha kısa sürede elde etmelerine yardımcı olmak için performansla ilgili en iyi uygulamalardan yararlanabilirsiniz.


  1. Burada listelenen maliyetler ABD doları cinsindendir. Tam fiyatlandırma bilgileri için lütfen Google Haritalar Platformu Faturalandırma sayfasına bakın.

Performansla ilgili en iyi uygulamalar

Aşağıdaki yönergelerde Otomatik Yer Tamamlama performansının optimize edilmesi için izlenecek yöntemler açıklanmaktadır:

  • Ülke kısıtlamaları ekleyin, konuma ağırlık verme, Otomatik Yer Tamamlama ayarınıza (programatik uygulamalar için) dil tercihinizi ekleyin bazı ipuçları vereceğim. Dil tercihi yapmanız gerekmez Dil tercihlerini kullanıcının tarayıcısından veya mobil cihazından seçtikleri için, widget'larla
  • Otomatik Yer Tamamlama'ya bir harita eşlik ediyorsa, konumu harita görünümüne göre değiştirebilirsiniz.
  • Kullanıcının Otomatik Tamamlama tahminlerinden birini seçmediği durumlarda, genellikle Bu tahminlerin hiçbiri istenen sonuç adresi olmadığından, orijinal daha alakalı sonuçlar almaya çalışmak için kullanıcı girdisi:
    • Kullanıcının yalnızca adres bilgilerini girmesini bekliyorsanız orijinal kullanıcı girişini yeniden kullanın Geocoding API'ye yapılan bir çağrıda.
    • Kullanıcının ada veya adrese göre belirli bir yer hakkında sorgu girmesini bekliyorsanız Yer Bulma isteği kullanın. Yalnızca belirli bir bölgede sonuç bekleniyorsa konuma ağırlık verme.
    Coğrafi Kodlama API'sini kullanmanın en iyi seçenek olacağı diğer senaryolar şunlardır:
    • Otomatik Yer Tamamlama desteğinin sunulduğu ülkelerdeki alt şirket içi adresleri giren kullanıcılar alt şirket adresleri eksik, ör. Çekya, Estonya ve Litvanya. Örneğin, Çekçe adres "Stroupežnického 3191/17, Praha" Place konumunda kısmi bir tahmin verir Otomatik tamamlama.
    • "23-30 29th St, Queens" gibi yol ön ekleriyle adresler giren kullanıcılar bir listesini oluştur: New York City veya "47-380 Kamehameha Hwy, Kaneohe" bir şehir manzarası var.

Sorun giderme

Çok çeşitli hatalar ortaya çıkabilse de, hatalarınızın çoğu uygulamadaki hatalar genellikle yapılandırma hatalarından (ör. örnek, yanlış API anahtarı kullanıldı veya API anahtarı yapılandırıldı yanlış) ya da kota hataları (uygulamanız kotasını aştı). Görüntüleyin Kullanım sınırları göz atın.

Otomatik tamamlama denetimleri kullanılırken ortaya çıkan hatalar didFailAutocompleteWithError() yöntemini kullanan çeşitli delege protokolleri kullanılır. İlgili içeriği oluşturmak için kullanılan Sağlanan NSError nesnesinin code özelliği, GMSPlacesErrorCode sıralaması.