Place Autocomplete

เลือกแพลตฟอร์ม: Android iOS JavaScript บริการเว็บ

บริการเติมข้อความอัตโนมัติใน Places SDK สําหรับ iOS จะแสดงผลการคาดคะเนสถานที่ตามข้อความค้นหาของผู้ใช้ เมื่อผู้ใช้พิมพ์ บริการเติมข้อความอัตโนมัติจะแสดงคําแนะนําเกี่ยวกับสถานที่ต่างๆ เช่น ธุรกิจ ที่อยู่ โค้ด Plus และจุดสนใจ

คุณเพิ่มการเติมข้อความอัตโนมัติลงในแอปได้ด้วยวิธีต่อไปนี้

การเพิ่มการควบคุมการเติมข้อความอัตโนมัติ

การควบคุม UI ที่เติมข้อความอัตโนมัติคือกล่องโต้ตอบการค้นหาที่มีฟังก์ชันเติมข้อความอัตโนมัติในตัว เมื่อผู้ใช้ป้อนข้อความค้นหา ตัวควบคุมจะแสดงรายการสถานที่ที่คาดคะเนให้เลือก เมื่อผู้ใช้เลือกแล้ว ระบบจะส่งคืนอินสแตนซ์ GMSPlace ซึ่งแอปสามารถใช้เพื่อดูรายละเอียดเกี่ยวกับสถานที่ที่เลือกได้

คุณเพิ่มการควบคุม UI เติมข้อความอัตโนมัติลงในแอปได้ด้วยวิธีต่อไปนี้

การเพิ่มการควบคุมแบบเต็มหน้าจอ

ใช้การควบคุมแบบเต็มหน้าจอเมื่อคุณต้องการบริบทที่เป็นโมดัล โดย UI ที่เติมข้อความอัตโนมัติจะแทนที่ UI ของแอปชั่วคราวจนกว่าผู้ใช้จะเลือกแล้ว ฟังก์ชันการทํางานนี้ให้บริการโดยคลาส GMSAutocompleteViewController เมื่อผู้ใช้เลือกสถานที่ แอปจะได้รับโค้ดเรียกกลับ

วิธีเพิ่มการควบคุมโหมดเต็มหน้าจอลงในแอปมีดังนี้

  1. สร้างองค์ประกอบ UI ในแอปหลักเพื่อเปิดการควบคุม UI ที่เติมข้อความอัตโนมัติ เช่น เครื่องจัดการการแตะที่ UIButton
  2. ใช้โปรโตคอล GMSAutocompleteViewControllerDelegate ในตัวควบคุมมุมมองระดับบนสุด
  3. สร้างอินสแตนซ์ GMSAutocompleteViewController และมอบหมายตัวควบคุมมุมมองระดับบนสุดเป็นพร็อพเพอร์ตี้ผู้รับมอบสิทธิ์
  4. สร้าง GMSPlaceField เพื่อกําหนดประเภทข้อมูลสถานที่ที่จะแสดง
  5. เพิ่ม GMSAutocompleteFilter เพื่อจํากัดข้อความค้นหาเป็นประเภทสถานที่ที่ต้องการ
  6. นําเสนอGMSAutocompleteViewControllerโดยใช้ [self presentViewController...]
  7. จัดการตัวเลือกของผู้ใช้ในวิธีมอบสิทธิ์ didAutocompleteWithPlace
  8. ปิดตัวควบคุมในวิธีมอบสิทธิ์ didAutocompleteWithPlace, didFailAutocompleteWithError และ wasCancelled

ตัวอย่างต่อไปนี้แสดงวิธีเปิดใช้งานวิธีเดียว GMSAutocompleteViewController เพื่อตอบสนองต่อการที่ผู้ใช้แตะปุ่ม

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:NSSelectorFromString(@"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

การเพิ่มตัวควบคุมผลลัพธ์

ใช้ตัวควบคุมผลลัพธ์เมื่อคุณต้องการควบคุม UI การป้อนข้อความได้มากขึ้น ตัวควบคุมผลลัพธ์จะสลับการเปิดเผยรายการผลลัพธ์แบบไดนามิกโดยอิงตามโฟกัส UI อินพุต

วิธีเพิ่มตัวควบคุมผลลัพธ์ลงในแอป

  1. สร้าง GMSAutocompleteResultsViewController
  2. ใช้โปรโตคอล GMSAutocompleteResultsViewControllerDelegate ในตัวควบคุมมุมมองระดับบนสุด และกําหนดให้ตัวควบคุมมุมมองระดับบนสุดเป็นพร็อพเพอร์ตี้ผู้รับมอบสิทธิ์
  3. สร้างออบเจ็กต์ UISearchController ที่ส่งผ่านในGMSAutocompleteResultsViewController เป็นอาร์กิวเมนต์ตัวควบคุมผลลัพธ์
  4. ตั้งค่า GMSAutocompleteResultsViewController เป็นพร็อพเพอร์ตี้ searchResultsUpdater ของ UISearchController
  5. เพิ่ม searchBar สําหรับ UISearchController ลงใน UI ของแอป
  6. จัดการตัวเลือกของผู้ใช้ในวิธีมอบสิทธิ์ didAutocompleteWithPlace

คุณวางแถบค้นหาของ UISearchController ใน UI ของแอปได้หลายวิธี ดังนี้

การเพิ่มแถบค้นหาลงในแถบนําทาง

ตัวอย่างโค้ดต่อไปนี้แสดงการเพิ่มตัวควบคุมผลลัพธ์ การเพิ่ม searchBar ลงในแถบนําทาง และการจัดการการเลือกของผู้ใช้

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

การเพิ่มแถบค้นหาที่ด้านบนของมุมมอง

ตัวอย่างโค้ดต่อไปนี้แสดงการเพิ่ม searchBar ไปยังด้านบนของมุมมอง

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

โดยค่าเริ่มต้น UISearchController จะซ่อนแถบนําทางเมื่อนําเสนอ (ปิดใช้ได้) ในกรณีที่แถบนําทางแสดงและเป็นแบบทึบ UISearchController จะตั้งค่าตําแหน่งไม่ถูกต้อง

ใช้รหัสต่อไปนี้เพื่อแก้ไขปัญหา

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;

การเพิ่มแถบค้นหาโดยใช้ผลลัพธ์ของป๊อปอัป

ตัวอย่างโค้ดต่อไปนี้แสดงการวางแถบค้นหาที่ด้านขวาของแถบนําทาง และแสดงผลป๊อปอัป

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

การใช้แหล่งข้อมูลตาราง

หากแอปมี UI ข้อความที่ค้นหาแบบกําหนดเอง คุณใช้คลาส GMSAutocompleteTableDataSource เพื่อกระตุ้นมุมมองตารางที่แสดงผลลัพธ์ของตัวควบคุมมุมมองได้

วิธีใช้ GMSAutocompleteTableDataSource เป็นแหล่งข้อมูลและผู้รับมอบสิทธิ์ของ UITableView ในตัวควบคุมมุมมอง

  1. ใช้โปรโตคอล GMSAutocompleteTableDataSourceDelegate และ UISearchBarDelegate ในตัวควบคุมมุมมอง
  2. สร้างอินสแตนซ์ GMSAutocompleteTableDataSource และมอบหมายตัวควบคุมมุมมองเป็นพร็อพเพอร์ตี้ผู้รับมอบสิทธิ์
  3. ตั้งค่า GMSAutocompleteTableDataSource เป็นพร็อพเพอร์ตี้แหล่งข้อมูลและการมอบสิทธิ์ของอินสแตนซ์ UITableView ในตัวควบคุมมุมมอง
  4. ในตัวจัดการสําหรับการป้อนข้อความค้นหา ให้เรียก sourceTextHasChanged ใน GMSAutocompleteTableDataSource
  5. จัดการตัวเลือกของผู้ใช้ในวิธีมอบสิทธิ์ didAutocompleteWithPlace
  6. ปิดตัวควบคุมในวิธีมอบสิทธิ์ didAutocompleteWithPlace, didFailAutocompleteWithError,wasCancelled

ตัวอย่างโค้ดต่อไปนี้แสดงการใช้คลาส GMSAutocompleteTableDataSource เพื่อขับเคลื่อนมุมมองตารางของ UIViewController เมื่อมีการเพิ่ม UISearchBar แยกต่างหาก

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

      

การปรับแต่งข้อความและสีพื้นหลัง

คุณตั้งค่าสีของข้อความและพื้นหลังทั้งหมดในการควบคุม UI ของการเติมข้อความอัตโนมัติได้ เพื่อให้วิดเจ็ตตรงกับลักษณะการมองเห็นของแอปอย่างใกล้ชิดยิ่งขึ้น คุณสามารถตั้งค่าสีการควบคุม UI ได้ 2 วิธีดังนี้

โดยปกติแล้ว แอปจะใช้โปรโตคอล UIลักษณะที่ปรากฏ และวิธีการ SDK บางอย่างผสมกัน แผนภาพต่อไปนี้จะแสดงองค์ประกอบที่จัดรูปแบบได้

เติมสีตัวควบคุม UI อัตโนมัติ

ตารางต่อไปนี้แสดงองค์ประกอบ UI ทั้งหมด และระบุวิธีจัดรูปแบบแต่ละรายการ (โปรโตคอล UIลักษณะที่ปรากฏ หรือเมธอด SDK)

องค์ประกอบ UI วิธีการ วิธีการแต่งตัว
แต้มสีของแถบนําทาง (พื้นหลัง) โปรโตคอล UIลักษณะที่ปรากฏ โทร setBarTintColor ผ่านพร็อกซี UINavigationBar
สีแต้มของแถบการนําทาง (เคอร์เซอร์ข้อความในแถบค้นหาและปุ่มยกเลิก) โปรโตคอล UIลักษณะที่ปรากฏ โทร setTintColor ผ่านพร็อกซี UINavigationBar
สีข้อความของแถบค้นหา โปรโตคอล UIลักษณะที่ปรากฏ ตั้งค่า NSForegroundColorAttributeName ใน searchBarTextAttributes
สีแต้มของแถบค้นหา ไม่มีข้อมูล แถบค้นหาเป็นแบบโปร่งแสงและแสดงเป็นแถบนําทาง ในเวอร์ชันแรเงา
สีข้อความของตัวยึดตําแหน่งแถบค้นหา (ข้อความค้นหาเริ่มต้น) โปรโตคอล UIลักษณะที่ปรากฏ ตั้งค่า NSForegroundColorAttributeName ใน placeholderAttributes
ข้อความหลัก (ใช้ได้กับข้อความแสดงข้อผิดพลาดและข้อความ) เมธอด SDK โทรมาที่ primaryTextColor
ไฮไลต์ข้อความหลัก เมธอด SDK โทรมาที่ primaryTextHighlightColor
ข้อความรอง เมธอด SDK โทรมาที่ secondaryTextColor
ข้อผิดพลาดและข้อความ เมธอด SDK โทรมาที่ primaryTextColor
พื้นหลังเซลล์ของตาราง เมธอด SDK โทรมาที่ tableCellBackgroundColor
สีตัวคั่นเซลล์ของตาราง เมธอด SDK โทรมาที่ tableCellSeparatorColor
ปุ่ม "ลองอีกครั้ง" เมธอด SDK โทรมาที่ tintColor
สัญญาณบอกสถานะกิจกรรม (ไอคอนหมุนแสดงความคืบหน้า) โปรโตคอล UIลักษณะที่ปรากฏ โทร setColor ผ่านพร็อกซี UIActivityIndicatorView
โลโก้ "ขับเคลื่อนโดย Google" รูปภาพระบบคลาวด์ที่เป็นรูปเศร้า ไม่มีข้อมูล ระบบจะเลือกเวอร์ชันสีขาวหรือสีเทาโดยอัตโนมัติตามคอนทราสต์ของพื้นหลัง
แว่นขยายและไอคอนล้างข้อความในช่องข้อความของแถบค้นหา ไม่มีข้อมูล หากต้องการจัดรูปแบบ ให้แทนที่รูปภาพเริ่มต้นด้วยรูปภาพสีที่ต้องการ

การใช้โปรโตคอล UIลักษณะที่ปรากฏ

คุณใช้ โปรโตคอล UIลักษณะที่ปรากฏ เพื่อรับพร็อกซีลักษณะที่ปรากฏสําหรับองค์ประกอบ UI ที่ระบุ ซึ่งคุณสามารถใช้เพื่อตั้งค่าสีสําหรับองค์ประกอบ UI ได้ เมื่อทําการแก้ไข อินสแตนซ์ทั้งหมด ของเอลิเมนต์ UI แต่ละรายการจะได้รับผลกระทบ เช่นตัวอย่างต่อไปนี้ของทั่วโลกจะเปลี่ยนสีข้อความของชั้นเรียน UITextField เป็นสีเขียวเมื่อมีข้อมูลใน UISearchBar

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

โปรดดูข้อมูลเพิ่มเติมเกี่ยวกับการระบุค่าสีได้ที่การอ้างอิงคลาส UIColor

ข้อมูลโค้ดต่อไปนี้แสดงคําสั่งพร็อกซีทั้งหมดที่ต้องใช้ในการจัดรูปแบบทุกอย่างในการควบคุม UI ที่เติมข้อความอัตโนมัติแบบเต็มหน้าจอ เพิ่มโค้ดนี้ลงในเมธอด didFinishLaunchingWithOptions ใน 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;

การตั้งค่าพร็อพเพอร์ตี้รูปแบบการควบคุม UI

ชุดย่อยของเอลิเมนต์การควบคุม UI บางส่วนมีพร็อพเพอร์ตี้ที่ไม่ได้รับผลกระทบจากโปรโตคอล UIลักษณะที่ปรากฏ และต้องตั้งค่าโดยตรง ตัวอย่างโค้ดต่อไปนี้แสดงการกําหนดสีพื้นหน้าและพื้นหลัง และนําไปใช้กับอินสแตนซ์ควบคุม UI ที่ชื่อ acController เพิ่มโค้ดนี้ลงในเมธอด onLaunchClicked ใน 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;

การใช้การคาดการณ์สถานที่แบบเป็นโปรแกรม

คุณสร้าง UI การค้นหาที่กําหนดเองได้แทน UI ที่วิดเจ็ตเติมข้อความอัตโนมัติระบุไว้ หากต้องการทําเช่นนี้ แอปต้องคาดการณ์ ตําแหน่งโดยใช้โปรแกรม แอปของคุณรับรายการชื่อสถานที่และ/หรือที่อยู่ที่คาดคะเนได้โดยใช้วิธีใดวิธีหนึ่งต่อไปนี้

กำลังโทรหา GMSPlacesClient findAutocompletePredictionsFromQuery:

หากต้องการดูรายชื่อสถานที่และ/หรือที่อยู่ที่คาดคะเน ก่อนอื่นให้ระบุ GMSPlacesClient แล้วเรียกเมธอด GMSPlacesClient findAutocompletePredictionsFromQuery: ด้วยพารามิเตอร์ต่อไปนี้

  • สตริง autocompleteQuery ที่มีข้อความที่ผู้ใช้พิมพ์
  • GMSAutocompleteSessionToken ซึ่งใช้เพื่อระบุแต่ละเซสชัน แอปของคุณควรส่งโทเค็นเดียวกันสําหรับการเรียกคําขอเติมข้อความอัตโนมัติแต่ละครั้ง จากนั้นจะส่งโทเค็นดังกล่าวพร้อมรหัสสถานที่พร้อมกับการเรียกใช้ fetchPlacefromPlaceID: ในครั้งต่อๆ ไปเพื่อดึงรายละเอียดสถานที่สําหรับสถานที่ที่ผู้ใช้เลือก
  • GMSAutocompleteFilter เพื่อทําสิ่งต่อไปนี้
    • การให้น้ําหนักหรือจํากัดผลลัพธ์ไปยังภูมิภาคที่ระบุ
    • จํากัดผลลัพธ์ให้แสดงเฉพาะประเภทสถานที่ที่ต้องการ
    • ออบเจ็กต์ GMSPlaceLocationBias/ออบเจ็กต์การจํากัดการให้น้ําหนักผลลัพธ์กับพื้นที่ที่ระบุโดยขอบเขตละติจูดและลองจิจูด
  • วิธีติดต่อกลับเพื่อจัดการกับการคาดการณ์การส่งคืน

ตัวอย่างโค้ดด้านล่างแสดงการเรียกใช้ findAutocompletePredictionsFromQuery:

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 จะเรียกเมธอดเรียกกลับที่ระบุ ซึ่งจะส่งผ่านอาร์เรย์ของออบเจ็กต์ GMSAutocompletePrediction

ออบเจ็กต์ GMSAutocompletePrediction แต่ละรายการจะมีข้อมูลต่อไปนี้

  • attributedFullText – ข้อความทั้งหมดของการคาดการณ์ในรูปแบบ NSAttributedString เช่น "ซิดนีย์ โอเปร่าเฮาส์, ซิดนีย์, นิวเซาท์เวลส์, ออสเตรเลีย" ทุกช่วงข้อความที่ตรงกับอินพุตของผู้ใช้จะมีแอตทริบิวต์ kGMSAutocompleteMatchAttribute คุณใช้แอตทริบิวต์นี้เพื่อไฮไลต์ข้อความที่ตรงกันในคําค้นหาของผู้ใช้ได้ ดังที่แสดงด้านล่าง
  • placeID – รหัสสถานที่ของสถานที่ที่คาดการณ์ไว้ รหัสสถานที่เป็น ตัวระบุข้อความที่ระบุสถานที่แบบไม่ซ้ํากัน โปรดดูภาพรวมรหัสสถานที่เพื่อดูข้อมูลเพิ่มเติมเกี่ยวกับรหัสสถานที่
  • distanceMeters – ระยะทางตรงจาก origin ที่ระบุไปยังปลายทาง หากไม่ได้ตั้งค่าพร็อพเพอร์ตี้ origin ระบบจะไม่แสดงผลค่าระยะทาง

ตัวอย่างโค้ดต่อไปนี้แสดงวิธีไฮไลต์ข้อความตัวหนาในส่วนต่างๆ ของผลลัพธ์ที่ตรงกับข้อความค้นหาของผู้ใช้ โดยใช้ enumerateAttribute

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;
    

การใช้ตัวดึงข้อมูล

หากต้องการสร้างการควบคุมการเติมข้อความอัตโนมัติเองตั้งแต่ต้น ให้ใช้ GMSAutocompleteFetcher ซึ่งจะรวมวิธี autocompleteQuery ไว้ใน GMSPlacesClient ตัวดึงข้อมูลจะดันคําขอออก โดยจะแสดงผลลัพธ์เฉพาะข้อความที่ป้อนล่าสุดเท่านั้น และไม่มีองค์ประกอบ UI

โปรดทําตามขั้นตอนต่อไปนี้เพื่อใช้ GMSAutocompleteFetcher

  1. ใช้โปรโตคอล GMSAutocompleteFetcherDelegate
  2. สร้างออบเจ็กต์ GMSAutocompleteFetcher
  3. เรียก sourceTextHasChanged จากการดึงข้อมูลเป็นประเภทผู้ใช้
  4. จัดการการคาดการณ์และข้อผิดพลาดโดยใช้เมธอดโปรโตคอล didAutcompleteWithPredictions และ didFailAutocompleteWithError

ตัวอย่างโค้ดต่อไปนี้สาธิตการใช้ตัวดึงข้อมูลเพื่อใส่ข้อมูลที่ผู้ใช้ป้อนและแสดงการจับคู่สถานที่ในมุมมองข้อความ ฟังก์ชันในการเลือกสถานที่ ไม่ได้ระบุไว้ FetcherSampleViewController มาจาก UIViewController in 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

โทเค็นเซสชัน

โทเค็นเซสชันจะจัดกลุ่มคําค้นหาและเฟสการเลือกของการเติมข้อความอัตโนมัติของผู้ใช้ลงในเซสชันแยกกันเพื่อจุดประสงค์ในการเรียกเก็บเงิน เซสชันจะเริ่มต้นเมื่อผู้ใช้เริ่มพิมพ์คําค้นหา และสรุปเมื่อเลือกสถานที่ แต่ละเซสชันอาจมีการค้นหาได้หลายรายการ ตามด้วยการเลือกสถานที่ 1 แห่ง เมื่อสรุปเซสชันแล้ว โทเค็นจะใช้งานไม่ได้อีกต่อไป แอปของคุณต้องสร้างโทเค็นใหม่สําหรับแต่ละเซสชัน เราขอแนะนําให้ใช้โทเค็นเซสชันสําหรับ การเติมข้อความอัตโนมัติแบบเป็นโปรแกรมทั้งหมด (เมื่อคุณใช้ตัวควบคุมแบบเต็มหน้าจอ หรือตัวควบคุมผลลัพธ์ API จะจัดการการดําเนินการนี้โดยอัตโนมัติ)

Places SDK สําหรับ iOS ใช้ GMSAutocompleteSessionToken เพื่อระบุแต่ละเซสชัน แอปควรส่งโทเค็นเซสชันใหม่เมื่อเริ่มต้นเซสชันใหม่แต่ละเซสชัน จากนั้นส่งโทเค็นเดียวกันนั้นพร้อมรหัสสถานที่ในการเรียกใช้ fetchPlacefromPlaceID: ครั้งถัดไปเพื่อเรียกข้อมูลรายละเอียดสถานที่สําหรับสถานที่ที่ผู้ใช้เลือก

ดูข้อมูลเพิ่มเติมเกี่ยวกับโทเค็นเซสชัน

ใช้รหัสต่อไปนี้เพื่อสร้างโทเค็นเซสชันใหม่

let token: GMSAutocompleteSessionToken = GMSAutocompleteSessionToken.init()

ขีดจำกัดการใช้งาน

การแสดงการระบุแหล่งที่มาในแอปของคุณ

  • หากแอปของคุณใช้บริการเติมข้อความอัตโนมัติด้วยโปรแกรม UI ต้องแสดงการระบุแหล่งที่มา "ขับเคลื่อนโดย Google" หรือปรากฏในแผนที่ที่เป็นแบรนด์ของ Google
  • หากแอปของคุณใช้การควบคุม UI ที่เติมข้อความอัตโนมัติ คุณไม่จําเป็นต้องดําเนินการใดๆ เพิ่มเติม (การระบุแอตทริบิวต์ที่จําเป็นจะแสดงโดยค่าเริ่มต้น)
  • หากคุณดึงข้อมูลและแสดงข้อมูลสถานที่เพิ่มเติมหลังจากได้สถานที่ตามรหัสแล้ว คุณจะต้องแสดงแหล่งที่มาของบุคคลที่สามด้วย

โปรดดูรายละเอียดเพิ่มเติมในเอกสารประกอบเกี่ยวกับการระบุแหล่งที่มา

การควบคุมตัวระบุกิจกรรมเครือข่าย

หากต้องการควบคุมตัวบ่งชี้กิจกรรมเครือข่ายในแถบสถานะของแอปพลิเคชัน คุณต้องใช้วิธีการมอบสิทธิ์ที่เหมาะสมสําหรับคลาสการเติมข้อความอัตโนมัติที่คุณกําลังใช้อยู่ รวมถึงเปิดและปิดตัวบ่งชี้เครือข่ายด้วยตนเอง

  • สําหรับ GMSAutocompleteViewController คุณต้องติดตั้งใช้งานวิธีการมอบสิทธิ์ didRequestAutocompletePredictions: และ didUpdateAutocompletePredictions:
  • สําหรับ GMSAutocompleteResultsViewController คุณต้องติดตั้งใช้งานวิธีการมอบสิทธิ์ didRequestAutocompletePredictionsForResultsController: และ didUpdateAutocompletePredictionsForResultsController:
  • สําหรับ GMSAutocompleteTableDataSource คุณต้องติดตั้งใช้งานวิธีการมอบสิทธิ์ didRequestAutocompletePredictionsForTableDataSource: และ didUpdateAutocompletePredictionsForTableDataSource:

การใช้วิธีการเหล่านี้และตั้งค่า [UIApplication sharedApplication].networkActivityIndicatorVisible เป็น YES และ NO ตามลําดับ แถบสถานะจะตรงกับ UI ของการเติมข้อความอัตโนมัติอย่างถูกต้อง

จํากัดผลลัพธ์ของการเติมข้อความอัตโนมัติ

คุณสามารถตั้งค่าการควบคุม UI เติมข้อความอัตโนมัติเพื่อจํากัดผลการค้นหาไปยังภูมิภาคทางภูมิศาสตร์ที่ต้องการ และ/หรือกรองผลลัพธ์ให้เหลือประเภทสถานที่อย่างน้อย 1 ประเภท หรือเฉพาะประเทศหรือกลุ่มประเทศที่ต้องการ เพื่อจํากัดผลลัพธ์ คุณสามารถดําเนินการดังต่อไปนี้:

  • หากต้องการผล (การให้น้ําหนัก) ผลลัพธ์ภายในภูมิภาคที่กําหนด ให้ตั้งค่า locationBias ใน GMSAutocompleteFilter (ผลลัพธ์บางรายการจากภายนอกภูมิภาคที่ระบุอาจยังคงส่งกลับ) หากตั้งค่า locationRestriction ไว้ด้วย ระบบจะไม่สนใจ locationBias
  • เมื่อต้องการแสดงเฉพาะผลลัพธ์ (จํากัด) ภายในภูมิภาคที่กําหนดไว้ ให้ตั้งค่า locationRestriction ใน GMSAutocompleteFilter (เฉพาะผลลัพธ์ภายในภูมิภาคที่ระบุเท่านั้นที่จะแสดงผล)

    • หมายเหตุ: ข้อจํากัดนี้มีผลกับเส้นทางทั้งหมดเท่านั้น อาจแสดงผลลัพธ์สังเคราะห์ที่อยู่นอกขอบเขตสี่เหลี่ยมผืนผ้า ตามเส้นทางที่ซ้อนทับกับการจํากัดสถานที่
  • ในการแสดงเฉพาะผลลัพธ์ที่สอดคล้องกับประเภทสถานที่หนึ่งๆ ให้ตั้งค่า types ใน GMSAutocompleteFilter (ตัวอย่างเช่น การระบุ TypeFilter.ADDRESS จะทําให้วิดเจ็ตแสดงผลลัพธ์ซึ่งมีที่อยู่ที่ถูกต้องเท่านั้น)

  • หากต้องการแสดงเฉพาะผลลัพธ์ภายใน 5 ประเทศที่ระบุ ให้ตั้งค่า 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);

กรองผลการค้นหาตามประเทศ

หากต้องการกรองผลลัพธ์ภายในไม่เกิน 5 ประเทศ ให้ตั้งค่า countries ใน GMSAutocompleteFilter ตามที่แสดงไว้ที่นี่

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

กรองผลลัพธ์ตามประเภทสถานที่หรือประเภทคอลเล็กชัน

จํากัดผลการค้นหาให้เป็นประเภทหรือคอลเล็กชันบางประเภทด้วยการตั้งค่าพร็อพเพอร์ตี้ types ของ GMSAutoCompleteFilter ใช้พร็อพเพอร์ตี้นี้เพื่อระบุตัวกรองที่แสดงในตาราง 1, 2 และ 3 ในประเภทสถานที่ หากไม่ระบุ ระบบจะแสดงผลทุกประเภท

ในการระบุประเภทตัวกรองหรือประเภทคอลเล็กชัน ให้ทําดังนี้

  • ใช้พร็อพเพอร์ตี้ types เพื่อระบุค่า type ได้สูงสุด 5 ค่าจากตาราง 1 และตาราง 2 ที่แสดงบน ประเภทสถานที่ ค่าประเภทจะกําหนดโดยค่าคงที่ใน GMSPlaceType

  • ใช้พร็อพเพอร์ตี้ types เพื่อระบุคอลเล็กชันประเภทจากตารางที่ 3 ซึ่งแสดงในประเภทสถานที่ ค่าการรวบรวมประเภทจะกําหนดโดยค่าคงที่ใน GMSPlaceType

    คําขอจะมีเพียงประเภทเดียวจากตาราง 3 ในคําขอ หากคุณระบุค่าจากตาราง 3 คุณจะระบุค่าจากตาราง 1 หรือตาราง 2 ไม่ได้ เพราะหากพบข้อผิดพลาด ระบบจะแสดงข้อผิดพลาด

เช่น หากต้องการให้แสดงเฉพาะผลลัพธ์ที่สอดคล้องกับประเภทสถานที่ที่เฉพาะเจาะจง ให้ตั้งค่า types ใน GMSAutocompleteFilter ตัวอย่างต่อไปนี้แสดงให้เห็นการตั้งค่าตัวกรองให้แสดงเฉพาะผลลัพธ์ซึ่งมีที่อยู่ที่ถูกต้อง

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

การเพิ่มประสิทธิภาพการเติมข้อความอัตโนมัติของสถานที่

ส่วนนี้จะอธิบายแนวทางปฏิบัติแนะนําที่จะช่วยให้คุณใช้ประโยชน์จากบริการเติมข้อความอัตโนมัติได้

หลักเกณฑ์ทั่วไปมีดังนี้

  • วิธีที่รวดเร็วที่สุดในการพัฒนาอินเทอร์เฟซผู้ใช้ที่ใช้งานได้คือ ใช้วิดเจ็ตเติมข้อความอัตโนมัติใน Maps JavaScript API, SDK สําหรับการเติมข้อความอัตโนมัติของ Places สําหรับ Android หรือ การควบคุม UI ของการเติมข้อความอัตโนมัติของ SDK สําหรับ iOS
  • ทําความเข้าใจช่องข้อมูลการเติมข้อความอัตโนมัติของ Place ที่สําคัญตั้งแต่ต้น
  • ช่องการให้น้ําหนักตําแหน่งและการจํากัดตําแหน่งเป็นตัวเลือกที่ไม่บังคับ แต่อาจมีผลกระทบอย่างมากต่อประสิทธิภาพการเติมข้อความอัตโนมัติ
  • ใช้การจัดการข้อผิดพลาดเพื่อดูแลให้แอปลดระดับอย่างสุภาพหาก API แสดงข้อผิดพลาด
  • ตรวจสอบว่าแอปมีการจัดการเมื่อไม่มีการเลือกและเสนอวิธีดําเนินการต่อแก่ผู้ใช้

แนวทางปฏิบัติที่ดีที่สุดในการเพิ่มประสิทธิภาพต้นทุน

การเพิ่มประสิทธิภาพต้นทุนพื้นฐาน

หากต้องการเพิ่มประสิทธิภาพค่าใช้จ่ายในการใช้บริการเติมข้อความสถานที่โดยอัตโนมัติ ให้ใช้มาสก์ของช่องในรายละเอียดสถานที่และวิดเจ็ตการเติมข้อความอัตโนมัติเพื่อแสดงผลเฉพาะช่องข้อมูลสถานที่ที่คุณต้องการ

การเพิ่มประสิทธิภาพต้นทุนขั้นสูง

โปรดพิจารณาการใช้การเติมข้อความอัตโนมัติของ Place แบบเป็นโปรแกรมเพื่อเข้าถึงการกําหนดราคาต่อคําขอและขอผลลัพธ์ของ Geocoding API เกี่ยวกับสถานที่ที่เลือกแทนรายละเอียดสถานที่ การกําหนดราคาต่อคําขอที่จับคู่กับ Geocoding API จะมีประสิทธิภาพด้านราคามากกว่าต่อเซสชัน (ตามเซสชัน) หากเป็นไปตามเงื่อนไขทั้งสองข้อต่อไปนี้

  • หากคุณต้องการเพียงละติจูด/ลองจิจูดหรือที่อยู่ของสถานที่ที่ผู้ใช้เลือกเท่านั้น Geocoding API จะส่งข้อมูลนี้ให้คุณในการเรียกรายละเอียดสถานที่น้อยกว่า
  • หากผู้ใช้เลือกการคาดคะเนการเติมข้อความอัตโนมัติภายในโดยเฉลี่ยแล้ว 4 คําขอในการเติมข้อความอัตโนมัติหรือน้อยกว่านั้น การกําหนดราคาต่อคําขออาจคุ้มค่ากว่าการกําหนดราคาต่อเซสชัน
หากต้องการความช่วยเหลือในการเลือกการใช้การเติมข้อความอัตโนมัติที่ตรงกับความต้องการของคุณ ให้เลือกแท็บที่ตรงกับคําตอบสําหรับคําถามต่อไปนี้

แอปพลิเคชันของคุณต้องการข้อมูลอื่นนอกเหนือจากที่อยู่และละติจูด/ลองจิจูดของการคาดการณ์ที่เลือกใช่ไหม

ใช่ ต้องการรายละเอียดเพิ่มเติม

ใช้การเติมข้อความอัตโนมัติตามตําแหน่งโดยอิงจากรายละเอียดสถานที่
เนื่องจากแอปพลิเคชันของคุณต้องการรายละเอียดสถานที่ เช่น ชื่อสถานที่ สถานะธุรกิจ หรือเวลาทําการ การใช้งานการเติมข้อความอัตโนมัติจากสถานที่จึงควรใช้โทเค็นเซสชัน (แบบเป็นโปรแกรมหรือวิดเจ็ต JavaScript, Android หรือ iOS) รวมค่าใช้จ่ายทั้งหมด $0.017 ต่อเซสชัน บวกด้วย SKU ของข้อมูลสถานที่ โดยขึ้นอยู่กับช่องข้อมูลสถานที่ 1}

การใช้งานวิดเจ็ต
การจัดการเซสชันจะสร้างขึ้นโดยอัตโนมัติในวิดเจ็ต JavaScript, Android หรือ iOS ซึ่งรวมทั้งคําขอเติมข้อความอัตโนมัติของสถานที่และคําขอรายละเอียดสถานที่ในการคาดการณ์ที่เลือก อย่าลืมระบุพารามิเตอร์ fields เพื่อให้แน่ใจว่าคุณกําลังขอช่องข้อมูลที่คุณต้องการเท่านั้น

การใช้งานแบบเป็นโปรแกรม
ใช้โทเค็นเซสชันกับคําขอการเติมข้อความอัตโนมัติใน Place ของคุณ เมื่อขอรายละเอียดสถานที่เกี่ยวกับการคาดการณ์ที่เลือก ให้ใส่พารามิเตอร์ต่อไปนี้ด้วย

  1. รหัสสถานที่จากการตอบกลับการเติมข้อความสถานที่โดยอัตโนมัติ
  2. โทเค็นเซสชันที่ใช้ในคําขอเติมข้อความสถานที่โดยอัตโนมัติ
  3. พารามิเตอร์ fields ที่ระบุช่องข้อมูลสถานที่ที่คุณต้องการ

ไม่ ต้องการเพียงที่อยู่และตําแหน่งเท่านั้น

Geocoding API อาจเป็นตัวเลือกที่มีค่าใช้จ่ายมากกว่ารายละเอียดสถานที่สําหรับแอปพลิเคชันของคุณ ทั้งนี้ขึ้นอยู่กับประสิทธิภาพของการเติมข้อความอัตโนมัติจาก Place ของคุณ ประสิทธิภาพการเติมข้อความอัตโนมัติของแอปพลิเคชันจะแตกต่างกันไปขึ้นอยู่กับสิ่งที่ผู้ใช้ป้อน ตําแหน่งที่ใช้แอปพลิเคชัน และการใช้งานแนวทางปฏิบัติที่ดีที่สุดสําหรับการเพิ่มประสิทธิภาพ

ตอบคําถามต่อไปนี้เพื่อวิเคราะห์จํานวนอักขระที่ผู้ใช้พิมพ์โดยเฉลี่ยก่อนเลือกการคาดคะเนการเติมข้อความอัตโนมัติใน Place ในแอปพลิเคชันของคุณ

โดยเฉลี่ยแล้ว ผู้ใช้ของคุณเลือกการคาดคะเนการเติมข้อความอัตโนมัติของสถานที่ภายในคําขอไม่เกิน 4 คําขอใช่ไหม

ใช่

เติมข้อความอัตโนมัติในสถานที่โดยใช้โปรแกรมโดยไม่มีโทเค็นเซสชัน และเรียกใช้ Geocoding API ในการคาดการณ์สถานที่ที่เลือก
Geocoding API จะส่งที่อยู่และพิกัดละติจูด/ลองจิจูดให้ $0.005 ต่อคําขอ การขอ เติมข้อความอัตโนมัติเกี่ยวกับสถานที่ - คําขอ 4 ครั้งมีค่าใช้จ่าย 0.40 บาท ค่าใช้จ่ายรวมของคําขอ 4 รายการบวกกับการเรียกใช้ API การระบุพิกัดทางภูมิศาสตร์ 1 ครั้งเกี่ยวกับการคาดการณ์สถานที่ที่เลือกจะเป็น 10.60 บาท ซึ่งต่ํากว่าราคาการเติมข้อความอัตโนมัติต่อเซสชัน 0.4 บาท1

ลองใช้แนวทางปฏิบัติแนะนําเกี่ยวกับประสิทธิภาพเพื่อช่วยให้ผู้ใช้ได้รับการคาดคะเนที่ต้องการโดยใช้อักขระน้อยลง

ไม่ได้

ใช้การเติมข้อความอัตโนมัติตามตําแหน่งโดยอิงจากรายละเอียดสถานที่
เนื่องจากจํานวนคําขอโดยเฉลี่ยที่คุณคาดไว้ก่อนที่ผู้ใช้จะเลือกการคาดคะเนการเติมข้อความอัตโนมัตินั้นเกินค่าใช่จ่ายต่อเซสชัน การใช้งานการเติมข้อความอัตโนมัติของ Place ของคุณจึงควรใช้โทเค็นเซสชันสําหรับทั้งคําขอการเติมข้อความอัตโนมัติจากสถานที่และคําขอรายละเอียดสถานที่ที่เกี่ยวข้องรวมเป็น $0.017 ต่อเซสชัน1

การใช้งานวิดเจ็ต
การจัดการเซสชันจะสร้างขึ้นโดยอัตโนมัติในวิดเจ็ต JavaScript, Android หรือ iOS ซึ่งรวมทั้งคําขอเติมข้อความอัตโนมัติของสถานที่และคําขอรายละเอียดสถานที่ในการคาดการณ์ที่เลือก โปรดระบุพารามิเตอร์ fields เพื่อให้แน่ใจว่าคุณร้องขอเฉพาะช่องข้อมูลพื้นฐาน

การใช้งานแบบเป็นโปรแกรม
ใช้โทเค็นเซสชันกับคําขอการเติมข้อความอัตโนมัติใน Place ของคุณ เมื่อขอรายละเอียดสถานที่เกี่ยวกับการคาดการณ์ที่เลือก ให้ใส่พารามิเตอร์ต่อไปนี้ด้วย

  1. รหัสสถานที่จากการตอบกลับการเติมข้อความสถานที่โดยอัตโนมัติ
  2. โทเค็นเซสชันที่ใช้ในคําขอเติมข้อความสถานที่โดยอัตโนมัติ
  3. พารามิเตอร์ fields ที่ระบุช่องข้อมูลพื้นฐาน เช่น ที่อยู่และเรขาคณิต

พิจารณาเลื่อนคําขอการเติมข้อความอัตโนมัติสถานที่
คุณใช้กลยุทธ์ต่างๆ ได้ เช่น เลื่อนคําขอเติมข้อความอัตโนมัติลงในสถานที่จนกว่าผู้ใช้จะพิมพ์อักขระ 3 หรือ 4 ตัวแรกแล้ว เพื่อให้แอปพลิเคชันส่งคําขอน้อยลง ตัวอย่างเช่น การส่งคําขอเติมข้อความอัตโนมัติให้กับอักขระแต่ละตัวหลังจาก ผู้ใช้พิมพ์อักขระตัวที่ 3 หมายความว่าหากผู้ใช้พิมพ์ 7 อักขระ แล้วเลือกการคาดคะเนที่คุณกําหนดคําขอ API การระบุพิกัดทางภูมิศาสตร์ 1 รายการ ค่าใช้จ่ายรวมคือ 0.01632 บาท (4 * 0.00283 การเติมข้อความอัตโนมัติต่อคําขอ + การระบุพิกัดทางภูมิศาสตร์ $0.005)1

หากคําขอที่หน่วงเวลาอาจทําให้คําขอแบบเป็นโปรแกรมเฉลี่ยต่ํากว่า 4 ทําตามได้โดยทําตามคําแนะนําเกี่ยวกับการเติมข้อความอัตโนมัติในสถานที่ด้วย Geocoding API โปรดทราบว่าผู้ใช้ที่อาจคาดหวังว่าจะเห็นคําขอที่มีการหน่วงเวลาคือการกดแป้นพิมพ์แต่ละครั้ง

ลองใช้แนวทางปฏิบัติแนะนําเกี่ยวกับประสิทธิภาพเพื่อช่วยให้ผู้ใช้ได้รับการคาดคะเนที่ต้องการโดยใช้อักขระจํานวนน้อยลง


  1. ค่าใช้จ่ายที่แสดงในรายการนี้แสดงเป็นสกุลเงิน USD โปรดดูข้อมูลราคาเต็มในหน้าการเรียกเก็บเงิน Google Maps Platform

แนวทางปฏิบัติแนะนําสําหรับประสิทธิภาพ

หลักเกณฑ์ต่อไปนี้อธิบายวิธีการเพิ่มประสิทธิภาพการเติมข้อความอัตโนมัติของสถานที่

  • เพิ่มข้อจํากัดด้านประเทศ การให้น้ําหนักตําแหน่ง และ (สําหรับการใช้แบบเป็นโปรแกรม) ในการตั้งค่าการใช้การเติมข้อความอัตโนมัติของ Place ของคุณ ค่ากําหนดภาษาไม่จําเป็นต้องใช้กับวิดเจ็ตเนื่องจากเลือกค่ากําหนดภาษาจากเบราว์เซอร์หรืออุปกรณ์เคลื่อนที่ของผู้ใช้
  • หากการเติมข้อความอัตโนมัติของสถานที่แสดงพร้อมกับแผนที่ คุณสามารถตั้งตําแหน่งการให้น้ําหนักตามวิวพอร์ตแผนที่ได้
  • ในกรณีที่ผู้ใช้ไม่ได้เลือกการคาดคะเนจากการเติมข้อความอัตโนมัติ โดยทั่วไปจะเป็นเพียงเพราะการคาดคะเนเหล่านี้ไม่ใช่ที่อยู่ผลลัพธ์ที่ต้องการ คุณจึงนําอินพุตเดิมของผู้ใช้มาใช้ซ้ําได้เพื่อให้ได้ผลลัพธ์ที่เกี่ยวข้องมากขึ้น ดังนี้
    • หากคุณคาดหวังให้ผู้ใช้ป้อนเฉพาะข้อมูลที่อยู่ ให้ใช้อินพุตเดิมของผู้ใช้ซ้ําในการเรียก Geocoding API
    • หากคุณให้ผู้ใช้ป้อนการค้นหาสําหรับสถานที่ที่ต้องการตามชื่อหรือที่อยู่ ให้ใช้ค้นหาคําขอสถานที่ หากคาดว่าจะพบผลลัพธ์ในบางภูมิภาคเท่านั้น ให้ใช้การให้น้ําหนักตําแหน่ง
    สถานการณ์อื่นๆ เมื่อวิธีที่ดีที่สุดคือการเปลี่ยนไปใช้ Geocoding API ได้แก่
    • ผู้ใช้ป้อนที่อยู่ย่อยในประเทศที่การรองรับสถานที่ในการเติมข้อความย่อยของ Place ไม่สมบูรณ์ เช่น เช็กเกีย เอสโตเนีย และลิทัวเนีย เช่น ที่อยู่เช็ก "Stroupežnického 3191/17, Praha" ให้ผลการคาดคะเนบางส่วนในการเติมข้อความอัตโนมัติของสถานที่
    • ผู้ใช้ป้อนที่อยู่ที่มีคํานําหน้าส่วนถนน เช่น "23-30 29th St, Queens" ในนิวยอร์กซิตี้ หรือ "47-380 Kamehameha Hwy, Kaneohe" บนเกาะคาไวใน Hawai'i

การแก้ปัญหา

แม้ว่าข้อผิดพลาดที่หลากหลายอาจเกิดขึ้นได้ แต่ข้อผิดพลาดส่วนใหญ่ที่แอปมีโอกาสได้รับมักจะเกิดจากข้อผิดพลาดในการกําหนดค่า (เช่น มีการใช้คีย์ API ที่ไม่ถูกต้อง หรือกําหนดค่าคีย์ API ไม่ถูกต้อง) หรือข้อผิดพลาดเกี่ยวกับโควต้า (แอปใช้โควต้าเกินโควต้า) ดูข้อมูลเพิ่มเติมเกี่ยวกับโควต้าได้ที่ขีดจํากัดการใช้งาน

ข้อผิดพลาดที่เกิดขึ้นโดยใช้การควบคุมการเติมข้อความอัตโนมัติจะปรากฏในเมธอด didFailAutocompleteWithError() ของโปรโตคอลการมอบอํานาจต่างๆ พร็อพเพอร์ตี้ code ของออบเจ็กต์ NSError ที่ระบุมีการตั้งค่าเป็นหนึ่งในค่าการแจงนับ GMSPlacesErrorCode