השלמה אוטומטית למקומות (דור קודם) מחזירה חיזויים של מקומות בתגובה לשאילתות חיפוש של משתמשים. בזמן שהמשתמש מקליד, שירות ההשלמה האוטומטית מחזיר הצעות למקומות כמו עסקים, כתובות, Plus Codes ונקודות עניין.
אפשר להוסיף השלמה אוטומטית לאפליקציה בדרכים הבאות:
- הוסיפו רכיב אינטראקטיבי להשלמה אוטומטית כדי לחסוך זמן פיתוח ולוודא שחוויית המשתמש תהיה עקבית.
- קבלת תחזיות של מקומות באופן פרוגרמטי כדי ליצור חוויית משתמש מותאמת אישית.
הוספת רכיב אינטראקטיבי להשלמה אוטומטית

הרכיב האינטראקטיבי של ההשלמה האוטומטית הוא תיבת דו-שיח של חיפוש עם פונקציונליות מובנית של השלמה אוטומטית. כשהמשתמש מזין מונחי חיפוש, הפקד מציג רשימה של מקומות חזויים לבחירה. כשהמשתמש בוחר מקום, מוחזר מופע של GMSPlace, והאפליקציה יכולה להשתמש בו כדי לקבל פרטים על המקום שנבחר.
אתם יכולים להוסיף לאפליקציה את הרכיב האינטראקטיבי של ההשלמה האוטומטית בדרכים הבאות:
הוספת פקד למסך מלא
השתמשו בפקד המסך המלא כשאתם רוצים הקשר מודאלי, שבו ממשק המשתמש של ההשלמה האוטומטית מחליף באופן זמני את ממשק המשתמש של האפליקציה עד שהמשתמש בוחר את מה שהוא רוצה. הפונקציונליות הזו מסופקת על ידי המחלקה GMSAutocompleteViewController. כשהמשתמש בוחר מקום, האפליקציה מקבלת קריאה חוזרת (callback).
כדי להוסיף לאפליקציה פקד למסך מלא:
- יוצרים רכיב בממשק המשתמש באפליקציה הראשית כדי להפעיל את הרכיב האינטראקטיבי של ההשלמה האוטומטית, למשל handler של מגע ב-
UIButton. - מטמיעים את הפרוטוקול
GMSAutocompleteViewControllerDelegateב-parent view controller. - יוצרים מופע של
GMSAutocompleteViewControllerומקצים את בקר התצוגה הראשי כמאפיין הנציג. - יוצרים
GMSPlaceFieldכדי להגדיר את סוגי הנתונים של המקומות שיוחזרו. - מוסיפים
GMSAutocompleteFilterכדי להגביל את השאילתה לסוג מסוים של מקום. - מציגים את
GMSAutocompleteViewControllerבאמצעות[self presentViewController...]. - מטפלים בבחירה של המשתמש ב-delegate method של
didAutocompleteWithPlace. - סוגרים את ה-controller בשיטות ה-delegate
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 = [kGMSPlaceTypeCollectionAddress] autocompleteController.autocompleteFilter = filter // Display the autocomplete view controller. present(autocompleteController, animated: true, completion: nil) } // Add a button to the view. func makeButton() { let btnLaunchAc = UIButton(frame: CGRect(x: 5, y: 150, width: 300, height: 35)) btnLaunchAc.backgroundColor = .blue btnLaunchAc.setTitle("Launch autocomplete", for: .normal) btnLaunchAc.addTarget(self, action: #selector(autocompleteClicked), for: .touchUpInside) self.view.addSubview(btnLaunchAc) } } extension ViewController: GMSAutocompleteViewControllerDelegate { // Handle the user's selection. func viewController(_ viewController: GMSAutocompleteViewController, didAutocompleteWith place: GMSPlace) { print("Place name: \(place.name)") print("Place ID: \(place.placeID)") print("Place attributions: \(place.attributions)") dismiss(animated: true, completion: nil) } func viewController(_ viewController: GMSAutocompleteViewController, didFailAutocompleteWithError error: Error) { // TODO: handle the error. print("Error: ", error.localizedDescription) } // User canceled the operation. func wasCancelled(_ viewController: GMSAutocompleteViewController) { dismiss(animated: true, completion: nil) } // Turn the network activity indicator on and off again. func didRequestAutocompletePredictions(_ viewController: GMSAutocompleteViewController) { UIApplication.shared.isNetworkActivityIndicatorVisible = true } func didUpdateAutocompletePredictions(_ viewController: GMSAutocompleteViewController) { UIApplication.shared.isNetworkActivityIndicatorVisible = false } }
Objective-C
#import "ViewController.h" @import GooglePlaces; @interface ViewController () <GMSAutocompleteViewControllerDelegate> @end @implementation ViewController { GMSAutocompleteFilter *_filter; } - (void)viewDidLoad { [super viewDidLoad]; [self makeButton]; } // Present the autocomplete view controller when the button is pressed. - (void)autocompleteClicked { GMSAutocompleteViewController *acController = [[GMSAutocompleteViewController alloc] init]; acController.delegate = self; // Specify the place data types to return. GMSPlaceField fields = (GMSPlaceFieldName | GMSPlaceFieldPlaceID); acController.placeFields = fields; // Specify a filter. _filter = [[GMSAutocompleteFilter alloc] init]; _filter.types = @[ kGMSPlaceTypeBank ]; acController.autocompleteFilter = _filter; // Display the autocomplete view controller. [self presentViewController:acController animated:YES completion:nil]; } // Add a button to the view. - (void)makeButton{ UIButton *btnLaunchAc = [UIButton buttonWithType:UIButtonTypeCustom]; [btnLaunchAc addTarget:self action:@selector(autocompleteClicked) forControlEvents:UIControlEventTouchUpInside]; [btnLaunchAc setTitle:@"Launch autocomplete" forState:UIControlStateNormal]; btnLaunchAc.frame = CGRectMake(5.0, 150.0, 300.0, 35.0); btnLaunchAc.backgroundColor = [UIColor blueColor]; [self.view addSubview:btnLaunchAc]; } // Handle the user's selection. - (void)viewController:(GMSAutocompleteViewController *)viewController didAutocompleteWithPlace:(GMSPlace *)place { [self dismissViewControllerAnimated:YES completion:nil]; // Do something with the selected place. NSLog(@"Place name %@", place.name); NSLog(@"Place ID %@", place.placeID); NSLog(@"Place attributions %@", place.attributions.string); } - (void)viewController:(GMSAutocompleteViewController *)viewController didFailAutocompleteWithError:(NSError *)error { [self dismissViewControllerAnimated:YES completion:nil]; // TODO: handle the error. NSLog(@"Error: %@", [error description]); } // User canceled the operation. - (void)wasCancelled:(GMSAutocompleteViewController *)viewController { [self dismissViewControllerAnimated:YES completion:nil]; } // Turn the network activity indicator on and off again. - (void)didRequestAutocompletePredictions:(GMSAutocompleteViewController *)viewController { [UIApplication sharedApplication].networkActivityIndicatorVisible = YES; } - (void)didUpdateAutocompletePredictions:(GMSAutocompleteViewController *)viewController { [UIApplication sharedApplication].networkActivityIndicatorVisible = NO; } @end
הוספת פקד תוצאות
כדאי להשתמש בבקר תוצאות כשרוצים יותר שליטה בממשק המשתמש של קלט הטקסט. בקר התוצאות מחליף באופן דינמי את החשיפה של רשימת התוצאות על סמך המיקוד של ממשק המשתמש של הקלט.
כדי להוסיף בקר תוצאות לאפליקציה:
- יוצרים
GMSAutocompleteResultsViewController.- מטמיעים את הפרוטוקול
GMSAutocompleteResultsViewControllerDelegateב-parent view controller ומקצים את ה-parent view controller כמאפיין הנציג.
- מטמיעים את הפרוטוקול
- יוצרים אובייקט
UISearchControllerומעבירים אתGMSAutocompleteResultsViewControllerכארגומנט של בקר התוצאות. - מגדירים את
GMSAutocompleteResultsViewControllerכמאפייןsearchResultsUpdaterשלUISearchController. - מוסיפים את
searchBarעבורUISearchControllerלממשק המשתמש של האפליקציה. - מטפלים בבחירה של המשתמש ב-delegate method של
didAutocompleteWithPlace.
יש כמה דרכים להוסיף את שורת החיפוש של UISearchController לממשק המשתמש של האפליקציה:
- הוספת שורת חיפוש לסרגל הניווט
- הוספת שורת חיפוש לחלק העליון של תצוגה
- הוספת סרגל חיפוש עם תוצאות בחלון קופץ
הוספת שורת חיפוש לסרגל הניווט
בדוגמת הקוד הבאה מוצג איך מוסיפים בקר תוצאות, מוסיפים את 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; }
שימוש במקור נתונים של טבלה
אם לאפליקציה יש ממשק משתמש מותאם אישית לחיפוש טקסט, אתם יכולים להשתמש במחלקה GMSAutocompleteTableDataSource כדי להציג את תוצאות החיפוש בטבלה ב-view controller.
כדי להשתמש ב-GMSAutocompleteTableDataSource כמקור הנתונים וכנציג של UITableView ב-view controller:
- מטמיעים את הפרוטוקולים
GMSAutocompleteTableDataSourceDelegateו-UISearchBarDelegateב-view controller. - יוצרים מופע של
GMSAutocompleteTableDataSourceומקצים את בקר התצוגה כמאפיין הנציג. - מגדירים את
GMSAutocompleteTableDataSourceכמקור הנתונים ומאצילים את המאפיינים של המופעUITableViewב-view controller. - ב-handler של קלט טקסט החיפוש, קוראים ל-
sourceTextHasChangedב-GMSAutocompleteTableDataSource.- מטפלים בבחירה של המשתמש ב-delegate method של
didAutocompleteWithPlace.
- מטפלים בבחירה של המשתמש ב-delegate method של
- סוגרים את ה-controller ב-delegate methods
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
התאמה אישית של צבעי הטקסט והרקע
אתם יכולים להגדיר את הצבעים של כל הטקסטים והרקעים ברכיב האינטראקטיבי של ההשלמה האוטומטית, כדי שהווידג'ט יתאים יותר למראה הוויזואלי של האפליקציה. יש שתי דרכים להגדיר את הצבעים של הרכיבים האינטראקטיביים:
- באמצעות פרוטוקול UIAppearance המובנה של iOS, כדי לעצב באופן גלובלי את הרכיבים האינטראקטיביים כשאפשר. ההגדרות האלה חלות על הרבה מהרכיבים האינטראקטיביים, אבל לא על כולם.
- משתמשים ב-methods של ה-SDK במחלקות של הווידג'ט כדי להגדיר מאפיינים שלא נתמכים על ידי פרוטוקול UIAppearance.
בדרך כלל, האפליקציה תשתמש בשילוב כלשהו של פרוטוקול UIAppearance והשיטות של ה-SDK. בתרשים הבא מוצגים הרכיבים שאפשר לעצב:

בטבלה הבאה מפורטים כל הרכיבים בממשק המשתמש, ומצוין איך צריך לעצב כל אחד מהם (פרוטוקול UIAppearance או שיטת SDK).
| רכיב בממשק המשתמש | שיטה | רעיונות לסטיילינג |
|---|---|---|
| גוון סרגל הניווט (רקע) | פרוטוקול UIAppearance | קוראים לפונקציה setBarTintColor בשרת ה-proxy של UINavigationBar. |
| צבע הגוון של סרגל הניווט (סמן הטקסט של שורת החיפוש והלחצן "ביטול") | פרוטוקול UIAppearance | קוראים לפונקציה setTintColor בשרת ה-proxy של UINavigationBar. |
| צבע הטקסט של שורת החיפוש | פרוטוקול UIAppearance | מגדירים את NSForegroundColorAttributeName ב-searchBarTextAttributes. |
| גוון הצבע של שורת החיפוש | לא רלוונטי | שורת החיפוש שקופה למחצה, ומוצגת כגרסה מוצללת של סרגל הניווט. |
| צבע הטקסט לדוגמה בשורת החיפוש (טקסט החיפוש שמוגדר כברירת מחדל) | פרוטוקול UIAppearance | מגדירים את NSForegroundColorAttributeName ב-placeholderAttributes. |
| טקסט ראשי (מוחל גם על טקסט של שגיאות והודעות) | שיטת SDK | התקשרו אל primaryTextColor. |
| הדגשת הטקסט הראשי | שיטת SDK | התקשרו אל primaryTextHighlightColor. |
| טקסט משני | שיטת SDK | התקשרו אל secondaryTextColor. |
| טקסט של שגיאה והודעה | שיטת SDK | התקשרו אל primaryTextColor. |
| רקע של תא בטבלה | שיטת SDK | התקשרו אל tableCellBackgroundColor. |
| צבע הקו המפריד בין תאים בטבלה | שיטת SDK | התקשרו אל tableCellSeparatorColor. |
| כפתור "ניסיון חוזר" | שיטת SDK | התקשרו אל tintColor. |
| אינדיקטור של פעילות (ספינר התקדמות) | פרוטוקול UIAppearance | קוראים לפונקציה setColor בשרת ה-proxy של UIActivityIndicatorView. |
| לוגו של "מופעל על ידי Google", תמונה של ענן עצוב | לא רלוונטי | הגרסה הלבנה או האפורה נבחרת באופן אוטומטי על סמך הניגודיות של הרקע. |
| סמלים של זכוכית מגדלת וניקוי טקסט בשדה הטקסט של שורת החיפוש | לא רלוונטי | כדי לעצב, מחליפים את תמונות ברירת המחדל בתמונות בצבע הרצוי. |
שימוש בפרוטוקול UIAppearance
אתם יכולים להשתמש בפרוטוקול UIAppearance כדי לקבל את שרת ה-proxy של המראה של רכיב נתון בממשק המשתמש, ואז להשתמש בו כדי להגדיר את הצבע של הרכיב בממשק המשתמש. כשמבצעים שינוי, הוא משפיע על כל המופעים של רכיב מסוים בממשק המשתמש. לדוגמה, בקטע הקוד הבא, צבע הטקסט של כל המחלקות מסוג UITextField משתנה לירוק כשהן כלולות ב-UISearchBar:
[[UITextField appearanceWhenContainedIn:[UISearchBar class], nil] setDefaultTextAttributes:@{NSForegroundColorAttributeName:[UIColor greenColor]}];
למידע נוסף על הגדרת ערכי צבע, אפשר לעיין במאמר UIColor Class Reference.
קטעי הקוד הבאים מציגים את כל פקודות ה-proxy שצריך להשתמש בהן כדי לעצב את כל הרכיבים ב<b>רכיב אינטראקטיבי</b> של ההשלמה האוטומטית במסך מלא. מוסיפים את הקוד הזה ל-method 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;
הגדרת מאפייני סגנון של רכיבים אינטראקטיביים
לחלק מהרכיבים האינטראקטיביים יש מאפיינים שלא מושפעים מהפרוטוקול UIAppearance, ולכן צריך להגדיר אותם ישירות. בדוגמת הקוד הבאה מוגדרים צבעי חזית ורקע, והם מוחלים על מופע של רכיב אינטראקטיבי בשם acController. מוסיפים את הקוד הזה ל-method 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;
קבלת תחזיות לגבי מקומות באופן פרוגרמטי
אתם יכולים ליצור ממשק משתמש מותאם אישית לחיפוש, במקום להשתמש בממשק המשתמש של הווידג'ט להשלמה אוטומטית. כדי לעשות את זה, האפליקציה צריכה לקבל תחזיות לגבי מקומות באופן פרוגרמטי. האפליקציה יכולה לקבל רשימה של שמות מקומות או כתובות חזויים באחת מהדרכים הבאות:
מתבצעת התקשרות אל GMSPlacesClient findAutocompletePredictionsFromQuery:
כדי לקבל רשימה של שמות מקומות ו/או כתובות חזויים, קודם צריך ליצור מופע של GMSPlacesClient, ואז להפעיל את השיטה GMSPlacesClient
findAutocompletePredictionsFromQuery: עם הפרמטרים הבאים:
- מחרוזת
autocompleteQueryשמכילה את הטקסט שהמשתמש הקליד. GMSAutocompleteSessionToken, שמשמש לזיהוי כל סשן בנפרד. האפליקציה צריכה להעביר את אותו טוקן בכל קריאה לבקשת השלמה אוטומטית, ואז להעביר את הטוקן הזה, יחד עם מזהה מקום, בקריאה הבאה ל-fetchPlacefromPlaceID:כדי לאחזר את פרטי המקום שנבחר על ידי המשתמש.GMSAutocompleteFilterאל:- הטיה או הגבלה של התוצאות לאזור ספציפי.
- להגביל את התוצאות לסוג מסוים של מקום.
- אובייקט
GMSPlaceLocationBias/Restriction שמשפיע על התוצאות לפי אזור ספציפי שמוגדר על ידי גבולות של קווי רוחב ואורך.
- שיטת קריאה חוזרת (callback) לטיפול בתחזיות שהוחזרו.
בדוגמאות הקוד הבאות מוצגת קריאה ל-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 = [kGMSPlaceTypeBank] filter.locationBias = GMSPlaceRectangularLocationOption( northEastBounds, southWestBounds); placesClient?.findAutocompletePredictions(fromQuery: "cheesebu", filter: filter, sessionToken: token, callback: { (results, error) in if let error = error { print("Autocomplete error: \(error)") return } if let results = results { for result in results { print("Result \(result.attributedFullText) with placeID \(result.placeID)") } } })
Objective-C
/** * Create a new session token. Be sure to use the same token for calling * findAutocompletePredictionsFromQuery:, as well as the subsequent place details request. * This ensures that the user's query and selection are billed as a single session. */ GMSAutocompleteSessionToken *token = [[GMSAutocompleteSessionToken alloc] init]; // Create a type filter. GMSAutocompleteFilter *_filter = [[GMSAutocompleteFilter alloc] init]; _filter.types = @[ kGMSPlaceTypeBank ]; [_placesClient findAutocompletePredictionsFromQuery:@"cheesebu" filter:_filter sessionToken:token callback:^(NSArray<GMSAutocompletePrediction *> * _Nullable results, NSError * _Nullable error) { if (error != nil) { NSLog(@"An error occurred %@", [error localizedDescription]); return; } if (results != nil) { for (GMSAutocompletePrediction *result in results) { NSLog(@"Result %@ with PlaceID %@", result.attributedFullText, result.placeID); } } }];
ה-API מפעיל את שיטת הקריאה החוזרת שצוינה, ומעביר מערך של אובייקטים מסוג GMSAutocompletePrediction.
כל אובייקט GMSAutocompletePrediction מכיל את הפרטים הבאים:
-
attributedFullText– הטקסט המלא של החיזוי, בפורמט שלNSAttributedString. לדוגמה: "בית האופרה של סידני, סידני, ניו סאות' ויילס, אוסטרליה". לכל טווח טקסט שתואם לקלט של המשתמש יש מאפיין,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. הפונקציה fetcher מגבילה את הבקשות, ומחזירה רק תוצאות של טקסט החיפוש שהוזן לאחרונה. הוא לא מספק רכיבים בממשק המשתמש.
כדי להטמיע את GMSAutocompleteFetcher, פועלים לפי השלבים הבאים:
- מטמיעים את הפרוטוקול
GMSAutocompleteFetcherDelegate. - יוצרים אובייקט
GMSAutocompleteFetcher. - מפעילים את
sourceTextHasChangedעל ה-fetcher בזמן שהמשתמש מקליד. - מטפלים בחיזויים ובשגיאות באמצעות השיטות של הפרוטוקולים
didAutcompleteWithPredictionsו-didFailAutocompleteWithError.
בדוגמת הקוד הבאה אפשר לראות איך משתמשים באובייקט השליפה כדי לקבל קלט מהמשתמש ולהציג התאמות של מקומות בתצוגת טקסט. הפונקציונליות לבחירת מקום הושמטה. FetcherSampleViewController נגזר מ-UIViewController ב-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> @interface FetcherSampleViewController () <GMSAutocompleteFetcherDelegate> @end @implementation FetcherSampleViewController { UITextField *_textField; UITextView *_resultText; GMSAutocompleteFetcher* _fetcher; } - (void)viewDidLoad { [super viewDidLoad]; self.view.backgroundColor = [UIColor whiteColor]; self.edgesForExtendedLayout = UIRectEdgeNone; // Set bounds to inner-west Sydney Australia. CLLocationCoordinate2D neBoundsCorner = CLLocationCoordinate2DMake(-33.843366, 151.134002); CLLocationCoordinate2D swBoundsCorner = CLLocationCoordinate2DMake(-33.875725, 151.200349); GMSAutocompleteFilter *autocompleteFilter = [[GMSAutocompleteFilter alloc] init]; autocompleteFilter.locationRestriction = GMSPlaceRectangularLocationOption(neBoundsCorner, swBoundsCorner); // Create the fetcher. _fetcher = [[GMSAutocompleteFetcher alloc] initWithBounds:nil filter:filter]; _fetcher.delegate = self; // Set up the UITextField and UITextView. _textField = [[UITextField alloc] initWithFrame:CGRectMake(5.0f, 0, self.view.bounds.size.width - 5.0f, 44.0f)]; _textField.autoresizingMask = UIViewAutoresizingFlexibleWidth; [_textField addTarget:self action:@selector(textFieldDidChange:) forControlEvents:UIControlEventEditingChanged]; _resultText =[[UITextView alloc] initWithFrame:CGRectMake(0, 45.0f, self.view.bounds.size.width, self.view.bounds.size.height - 45.0f)]; _resultText.backgroundColor = [UIColor colorWithWhite:0.95f alpha:1.0f]; _resultText.text = @"No Results"; _resultText.editable = NO; [self.view addSubview:_textField]; [self.view addSubview:_resultText]; } - (void)textFieldDidChange:(UITextField *)textField { NSLog(@"%@", textField.text); [_fetcher sourceTextHasChanged:textField.text]; } #pragma mark - GMSAutocompleteFetcherDelegate - (void)didAutocompleteWithPredictions:(NSArray *)predictions { NSMutableString *resultsStr = [NSMutableString string]; for (GMSAutocompletePrediction *prediction in predictions) { [resultsStr appendFormat:@"%@\n", [prediction.attributedPrimaryText string]]; } _resultText.text = resultsStr; } - (void)didFailAutocompleteWithError:(NSError *)error { _resultText.text = [NSString stringWithFormat:@"%@", error.localizedDescription]; } @end
טוקנים לסשנים
טוקנים לסשנים מקבצים את שלבי השאילתה והבחירה של חיפוש בהשלמה אוטומטית של משתמש לסשן נפרד לצורכי חיוב. הסשן מתחיל כשהמשתמש מתחיל להקליד שאילתה, ומסתיים כשהוא בוחר מקום. בכל סשן יכולות להיות כמה שאילתות, ואחריהן בחירה של מקום אחד. בסיום הסשן, האסימון כבר לא תקף. האפליקציה צריכה ליצור אסימון חדש לכל סשן. מומלץ להשתמש בטוקנים לסשנים בכל הסשנים של ההשלמה האוטומטית הפרוגרמטית (כשמשתמשים בבקר של המסך המלא או בבקר של התוצאות, ה-API מטפל בזה באופן אוטומטי).
Places SDK ל-iOS משתמש ב-GMSAutocompleteSessionToken כדי לזהות כל סשן. האפליקציה צריכה להעביר טוקן לסשן חדש בתחילת כל סשן חדש, ואז להעביר את אותו טוקן, יחד עם מזהה מקום, בקריאה הבאה ל-fetchPlacefromPlaceID: כדי לאחזר את Place Details עבור המקום שנבחר על ידי המשתמש.
כדי ליצור טוקן חדש לסשן, משתמשים בקוד הבא:
let token: GMSAutocompleteSessionToken = GMSAutocompleteSessionToken.init()
מכסות שימוש
- השימוש ב-method
GMSPlacesClient findAutocompletePredictionsFromQueryכפוף למגבלות מדורגות על שאילתות. למידע נוסף על מגבלות השימוש
הצגת השיוך באפליקציה
- אם האפליקציה שלכם משתמשת בשירות ההשלמה האוטומטית באופן פרוגרמטי, בממשק המשתמש צריך להופיע ייחוס "מופעל על ידי Google" או שהשירות צריך להופיע במפה עם המיתוג של Google.
- אם האפליקציה שלכם משתמשת ברכיב האינטראקטיבי של ההשלמה האוטומטית, לא נדרשת פעולה נוספת (השיוך הנדרש מוצג כברירת מחדל).
- אם אתם מאחזרים ומציגים מידע נוסף על מקום אחרי אחזור מקום לפי מזהה, אתם צריכים להציג גם את הייחוסים של הצד השלישי.
לפרטים נוספים, קראו את המאמר בנושא שיוך (Attribution).
שליטה באינדיקטור של הפעילות ברשת
כדי לשלוט באינדיקטור של הפעילות ברשת בשורת הסטטוס של האפליקציות, צריך להטמיע את השיטות האופציונליות המתאימות של ה-delegate עבור המחלקה של ההשלמה האוטומטית שבה משתמשים, ולהפעיל או להשבית את האינדיקטור של הרשת בעצמכם.
- ב-
GMSAutocompleteViewControllerצריך להטמיע את ה-methodsdidRequestAutocompletePredictions:ו-didUpdateAutocompletePredictions:. - ב-
GMSAutocompleteResultsViewControllerצריך להטמיע את ה-methodsdidRequestAutocompletePredictionsForResultsController:ו-didUpdateAutocompletePredictionsForResultsController:. - ב-
GMSAutocompleteTableDataSourceצריך להטמיע את ה-methodsdidRequestAutocompletePredictionsForTableDataSource:ו-didUpdateAutocompletePredictionsForTableDataSource:.
אם תטמיעו את השיטות האלה ותגדירו את [UIApplication
sharedApplication].networkActivityIndicatorVisible ל-YES ואת NO בהתאמה, שורת הסטטוס תתאים לממשק המשתמש של ההשלמה האוטומטית.
הגבלת תוצאות ההשלמה האוטומטית
אתם יכולים להגדיר את הרכיב האינטראקטיבי של ההשלמה האוטומטית כך שיגביל את התוצאות לאזור גיאוגרפי ספציפי, ו/או לסנן את התוצאות לפי סוג מקום אחד או יותר, או לפי מדינה או מדינות ספציפיות. כדי להגביל את התוצאות, אתם יכולים:
- כדי להעדיף (להטות) תוצאות בתוך האזור המוגדר, מגדירים את
locationBiasב-GMSAutocompleteFilter(יכול להיות שעדיין יוחזרו תוצאות מסוימות מחוץ לאזור המוגדר). אם גם המדיניותlocationRestrictionמוגדרת, המערכת תתעלם מהמדיניותlocationBias. כדי להציג רק (להגביל) תוצאות בתוך האזור שהוגדר, מגדירים את
locationRestrictionבמצבGMSAutocompleteFilter(יוחזרו רק תוצאות בתוך האזור שהוגדר).- הערה: ההגבלה הזו חלה רק על מסלולים שלמים. יכול להיות שיוחזרו תוצאות סינתטיות שנמצאות מחוץ לגבולות המלבניים, על סמך מסלול שחופף להגבלת המיקום.
כדי להחזיר רק תוצאות שתואמות לסוג מקום מסוים, מגדירים את
typesב-GMSAutocompleteFilter(לדוגמה, אם מציינים את kGMSPlaceTypeCollectionAddress, הווידג'ט יחזיר רק תוצאות עם כתובת מדויקת).כדי להחזיר רק תוצאות בתוך עד חמש מדינות שצוינו, צריך להגדיר את
countriesב-GMSAutocompleteFilter.
הטיית תוצאות לאזור ספציפי
כדי להעדיף (להטות) תוצאות באזור המוגדר, מגדירים את locationBias ב-GMSAutocompleteFilter, כמו שמוצג כאן:
northEast = CLLocationCoordinate2DMake(39.0, -95.0); southWest =
CLLocationCoordinate2DMake(37.5, -100.0); GMSAutocompleteFilter *filter =
[[GMSAutocompleteFilter alloc] init]; filter.locationBias =
GMSPlaceRectangularLocationOption(northEast, southWest);
הגבלת התוצאות לאזור ספציפי
כדי להציג רק (להגביל) תוצאות באזור שהוגדר, מגדירים את locationRestriction ב-GMSAutocompleteFilter, כמו שמוצג כאן:
northEast = CLLocationCoordinate2DMake(39.0, -95.0); southWest =
CLLocationCoordinate2DMake(37.5, -100.0); GMSAutocompleteFilter *filter =
[[GMSAutocompleteFilter alloc] init]; filter.locationRestriction =
GMSPlaceRectangularLocationOption(northEast, southWest);
סינון התוצאות לפי מדינה
כדי לסנן תוצאות בתוך עד חמש מדינות שצוינו, מגדירים את countries ב-GMSAutocompleteFilter, כמו שמוצג כאן:
GMSAutocompleteFilter *filter = [[GMSAutocompleteFilter alloc] init];
filter.countries = @[ @"au", @"nz" ];
סינון התוצאות לפי סוג המקום או אוסף הסוגים
כדי להגביל את התוצאות לסוג מסוים או לאוסף של סוגים, מגדירים את המאפיין types של GMSAutoCompleteFilter.
השתמשו במאפיין הזה כדי לציין מסננים שמפורטים בטבלאות 1, 2 ו-3 בדף סוגי מקומות. אם לא מציינים סוג, מוחזרים כל הסוגים.
כדי לציין מסנן של סוג או של אוסף סוגים:
משתמשים במאפיין
typesכדי לציין עד חמישה ערכי type מטבלה 1 ומטבלה 2 שמוצגות בקטע סוגי מקומות. ערכי הסוגים מוגדרים על ידי הקבועים ב-GMSPlaceType.משתמשים במאפיין
typesכדי לציין אוסף סוגים מטבלה 3 שמוצגת בדף סוגי מקומות. הערכים של אוסף הסוגים מוגדרים על ידי הקבועים ב-GMSPlaceType.אפשר להשתמש בבקשה רק בסוג אחד מטבלה 3. אם מציינים ערך מטבלה 3, אי אפשר לציין ערך מטבלה 1 או מטבלה 2. אם תעשו זאת, תתרחש שגיאה.
לדוגמה, כדי להחזיר רק תוצאות שתואמות לסוג מקום מסוים, מגדירים את types ב-GMSAutocompleteFilter. בדוגמה הבאה מוצגת הגדרת המסנן כך שיחזיר רק תוצאות עם כתובת מדויקת:
GMSAutocompleteFilter *filter = [[GMSAutocompleteFilter alloc] init];
filter.types = @[ kGMSPlaceTypeAirport, kGMSPlaceTypeAmusementPark ];
אופטימיזציה של השלמה אוטומטית למקומות (גרסה קודמת)
בקטע הזה מתוארות שיטות מומלצות שיעזרו לכם להפיק את המקסימום משירות ההשלמה האוטומטית למקומות (הגרסה הקודמת).
הנה כמה הנחיות כלליות:
- הדרך המהירה ביותר לפתח ממשק משתמש פעיל היא להשתמש בווידג'ט השלמה אוטומטית למקומות (דור קודם) של Maps JavaScript API, בווידג'ט השלמה אוטומטית למקומות (דור קודם) של Places SDK ל-Android או ברכיב האינטראקטיבי השלמה אוטומטית למקומות (דור קודם) של Places SDK ל-iOS.
- חשוב להבין מהם שדות הנתונים החיוניים של השלמה אוטומטית למקומות (מדור קודם) כבר מההתחלה.
- השדות "העדפת מיקום" ו"הגבלת מיקום" הם אופציונליים, אבל יכולה להיות להם השפעה משמעותית על הביצועים של ההשלמה האוטומטית.
- כדאי להשתמש בטיפול בשגיאות כדי לוודא שהאפליקציה תפעל בצורה תקינה אם ה-API יחזיר שגיאה.
- חשוב לוודא שהאפליקציה מטפלת במקרים שבהם אין בחירה ומציעה למשתמשים דרך להמשיך.
שיטות מומלצות לאופטימיזציה של עלויות
אופטימיזציה בסיסית של עלויות
כדי להוזיל את עלות השימוש בשירות "השלמה אוטומטית למקומות (דור קודם)", אתם יכולים להשתמש במסכות שדות בווידג'טים של "פרטי מקומות (דור קודם)" ו"השלמה אוטומטית למקומות (דור קודם)" כדי להחזיר רק את שדות הנתונים של "השלמה אוטומטית למקומות (דור קודם)" שאתם צריכים.
אופטימיזציה מתקדמת של עלויות
כדאי לשקול הטמעה פרוגרמטית של השלמה אוטומטית למקומות (מדור קודם) כדי לגשת אל מק"ט: השלמה אוטומטית – תמחור לכל בקשה ולבקש תוצאות של Geocoding API לגבי המקום שנבחר במקום Place Details (מדור קודם). תמחור לכל בקשה בשילוב עם Geocoding API משתלם יותר מתמחור לכל סשן (מבוסס-סשן) אם שני התנאים הבאים מתקיימים:
- אם אתם צריכים רק את קווי האורך והרוחב או את הכתובת של המקום שהמשתמש בחר, Geocoding API מספק את המידע הזה בעלות נמוכה יותר מאשר קריאה ל-Place Details (דור קודם).
- אם המשתמשים בוחרים הצעה להשלמת החיפוש מתוך ממוצע של ארבע בקשות להשלמה אוטומטית למקומות (דור קודם) או פחות, תמחור לפי בקשה יכול להיות משתלם יותר מתמחור לפי סשן.
| מה צריך לכלול בבקשה | מספר ממוצע של בקשות להשלמה אוטומטית למקומות (מדור קודם) לפני שהמשתמש בוחר חיזוי | הטמעה מומלצת |
|---|---|---|
| פרטי מקום שאינם הכתובת והמיקום, כמו שם המקום, סטטוס העסק או שעות הפתיחה | ללא הגבלה | השלמה אוטומטית למקומות (דור קודם) מבוססת-סשן עם Place Details (דור קודם) |
| רק הכתובת וקו הרוחב/קו האורך של החיזוי שנבחר | ארבעה או פחות | השלמה אוטומטית למקומות (דור קודם) לכל בקשה עם Geocoding API |
| רק הכתובת וקו הרוחב/קו האורך של החיזוי שנבחר | יותר מ-4 | השלמה אוטומטית למקומות (דור קודם) מבוססת-סשן לאפליקציות של כתובות בלבד |
יכול להיות ש-Geocoding API יהיה חסכוני יותר בשביל האפליקציה שלכם מאשר Place Details (מדור קודם), בהתאם לביצועים של השימוש ב-Place Autocomplete (מדור קודם). היעילות של השלמה אוטומטית למקומות (דור קודם) בכל אפליקציה משתנה בהתאם למה שהמשתמשים מזינים, למקום שבו משתמשים באפליקציה, ולשאלה אם הוטמעו שיטות מומלצות לאופטימיזציה של הביצועים.
כדי למצוא את מספר הבקשות הממוצע לטבלה, צריך לנתח כמה תווים משתמש מקליד בממוצע לפני שהוא בוחר חיזוי של השלמה אוטומטית למקומות (מדור קודם) באפליקציה.
השלמה אוטומטית למקומות (דור קודם) מבוססת-סשן עם פרטי מקומות (דור קודם)
שימוש בהשלמה אוטומטית למקומות (גרסה קודמת) מבוססת-סשן עם פרטי מקומות (גרסה קודמת).
מכיוון שהאפליקציה שלך דורשת את Place Details (מדור קודם), כמו שם המקום, הסטטוס של העסק
או שעות הפעילות, ההטמעה של השלמה אוטומטית למקומות (מדור קודם) צריכה להשתמש בטוקן לסשן
(באופן פרוגרמטי או מובנה בווידג'טים של
JavaScript,
Android,
או iOS)
לכל סשן
בנוסף למק"טים רלוונטיים של Places Data,
בהתאם לשדות נתונים של נתוני המקומות שביקשת.1
הטמעת ווידג'ט
ניהול הסשנים מובנה באופן אוטומטי בווידג'טים של
JavaScript,
Android,
או iOS
. החיוב כולל גם את הבקשות של "השלמה אוטומטית למקומות (דור קודם)" וגם את הבקשה של "פרטי מקומות (דור קודם)" בחיזוי שנבחר. חשוב לציין את הפרמטר fields כדי לוודא שאתם מבקשים רק את שדות הנתונים של ההשלמה האוטומטית למקומות (דור קודם) שאתם צריכים.
הטמעה פרוגרמטית
משתמשים בטוקן לסשן בבקשות של השלמה אוטומטית למקומות (מדור קודם). כששולחים בקשה לקבלת פרטי מקום (ממשק קודם) לגבי החיזוי שנבחר, צריך לכלול את הפרמטרים הבאים:
- מזהה המקום מהתשובה של ההשלמה האוטומטית למקומות (גרסה קודמת)
- הטוקן לסשן שמשמש בבקשה של השלמה אוטומטית למקומות (מדור קודם)
- הפרמטר
fieldsשמציין את שדות הנתונים של ההשלמה האוטומטית למקומות (מדור קודם) שאתם צריכים
השלמה אוטומטית למקומות (דור קודם) לכל בקשה באמצעות Geocoding API
מטמיעים את השלמה אוטומטית למקומות (מדור קודם) באופן פרוגרמטי בלי טוקנים לסשן, וקוראים ל-Geocoding API בחיזוי המקום שנבחר.
Geocoding API מספק כתובות וקואורדינטות של קווי רוחב ואורך.
ביצוע של ארבע בקשות השלמה אוטומטית למקומות – לכל בקשה וקריאה אחת ל-Geocoding API לגבי החיזוי של המקום שנבחר, עולה פחות מהעלות לכל סשן של השלמה אוטומטית למקומות (מדור קודם).1
כדאי להשתמש בשיטות מומלצות לשיפור הביצועים כדי לעזור למשתמשים לקבל את החיזוי שהם מחפשים עם עוד פחות תווים.
השלמה אוטומטית למקומות (דור קודם) מבוססת-סשן לאפליקציות של כתובות בלבד
שימוש בהשלמה אוטומטית למקומות (גרסה קודמת) מבוססת-סשן עם פרטי מקומות (גרסה קודמת).
מכיוון שהמספר הממוצע של בקשות שאתם צופים שתשלחו לפני שהמשתמש יבחר חיזוי של השלמה אוטומטית למקומות (מדור קודם) גבוה מהעלות של תמחור לכל סשן, ההטמעה של השלמה אוטומטית למקומות (מדור קודם) צריכה להשתמש בטוקן לסשן גם לבקשות של השלמה אוטומטית למקומות (מדור קודם) וגם לבקשה המשויכת של Place Details (מדור קודם)
לכל סשן.
1
הטמעת ווידג'ט
ניהול הסשנים מובנה באופן אוטומטי בווידג'טים של
JavaScript,
Android,
או iOS.
החיוב כולל גם את הבקשות של "השלמה אוטומטית למקומות (דור קודם)" וגם את הבקשה של "פרטי מקום (דור קודם)" לחיזוי שנבחר. חשוב לציין את הפרמטר fields כדי לוודא שאתם מבקשים רק את השדות שאתם צריכים.
הטמעה פרוגרמטית
משתמשים בטוקן לסשן בבקשות של השלמה אוטומטית למקומות (מדור קודם).
כששולחים בקשה לקבלת Place Details (גרסה קודמת) לגבי החיזוי שנבחר,
צריך לכלול את הפרמטרים הבאים:
- מזהה המקום מהתשובה של ההשלמה האוטומטית למקומות (גרסה קודמת)
- הטוקן לסשן שמשמש בבקשה של השלמה אוטומטית למקומות (מדור קודם)
- הפרמטר
fieldsשמציין שדות של נתונים בסיסיים כמו כתובת וגיאומטריה
כדאי לשקול לעכב את הבקשות להשלמה אוטומטית למקומות (מדור קודם)
אפשר להשתמש באסטרטגיות כמו עיכוב של בקשה להשלמה אוטומטית למקומות (מדור קודם) עד שהמשתמש מקליד את שלושת או ארבעת התווים הראשונים, כדי שהאפליקציה תשלח פחות בקשות. לדוגמה, אם שולחים בקשות של השלמה אוטומטית למקומות (דור קודם) לכל תו אחרי שהמשתמש הקליד את התו השלישי, והמשתמש מקליד שבעה תווים ואז בוחר הצעה שעבורה אתם שולחים בקשה אחת של Geocoding API, העלות הכוללת תהיה עבור 4 בקשות של השלמה אוטומטית למקומות (דור קודם) + Geocoding.1
אם עיכוב הבקשות יכול להפחית את הממוצע של הבקשות הפרוגרמטיות לפחות מ-4, אתם יכולים לפעול לפי ההנחיות להטמעה של השלמה אוטומטית למקומות (מדור קודם) עם Geocoding API. חשוב לזכור שעיכוב בקשות יכול להיתפס כזמן אחזור על ידי המשתמש, שאולי מצפה לראות חיזויים בכל הקשה חדשה.
כדאי להשתמש בשיטות מומלצות לשיפור הביצועים כדי לעזור למשתמשים לקבל את החיזוי שהם מחפשים בפחות תווים.
-
למידע על העלויות, קראו את המחירונים של Google Maps Platform.
שיטות מומלצות לשיפור הביצועים
בהנחיות הבאות מוסבר איך לשפר את הביצועים של השלמה אוטומטית למקומות (דור קודם):
- מוסיפים להטמעה של Place Autocomplete (מדור קודם) הגבלות לפי מדינה, הטיה לפי מיקום והעדפת שפה (להטמעות פרוגרמטיות). אין צורך בהעדפת שפה בווידג'טים, כי הם בוחרים את העדפות השפה מהדפדפן או מהמכשיר הנייד של המשתמש.
- אם השירות "השלמה אוטומטית למקומות (דור קודם)" מלווה במפה, אתם יכולים להטות את המיקום לפי אזור התצוגה של המפה.
- במקרים שבהם המשתמש לא בוחר באחת מההצעות של ההשלמה האוטומטית למקומות (מדור קודם), בדרך כלל כי אף אחת מההצעות האלה היא לא הכתובת הרצויה, אתם יכולים להשתמש שוב בקלט המקורי של המשתמש כדי לנסות לקבל תוצאות רלוונטיות יותר:
- אם אתם מצפים שהמשתמש יזין רק פרטי כתובת, השתמשו שוב בקלט המקורי של המשתמש בקריאה ל-Geocoding API.
- אם אתם מצפים שהמשתמש יזין שאילתות לגבי מקום ספציפי לפי שם או כתובת, השתמשו בבקשה ל-Place Details (מדור קודם). אם התוצאות צפויות רק באזור ספציפי, השתמשו בהטיית מיקום.
- משתמשים שמזינים כתובות של יחידות משנה, כמו כתובות של יחידות או דירות ספציפיות בתוך בניין. לדוגמה, הכתובת בצ'כיה "Stroupežnického 3191/17, Praha" מניבה חיזוי חלקי בהשלמה אוטומטית למקומות (מדור קודם).
- משתמשים שמזינים כתובות עם קידומות של קטעי כביש, כמו "23-30 29th St, Queens" בניו יורק או "47-380 Kamehameha Hwy, Kaneohe" באי קאואיי שבהוואי.
הטיה לפי מיקום
כדי להטות את התוצאות לאזור מסוים, מעבירים פרמטר location ופרמטר radius. ההגדרה הזו מנחה את ההשלמה האוטומטית למקומות (מדור קודם) להעדיף הצגת תוצאות בתוך האזור שהוגדר. יכול להיות שיוצגו תוצאות מחוץ לאזור שהוגדר. אפשר להשתמש בפרמטר includedRegionCodes כדי לסנן את התוצאות כך שיוצגו רק המקומות במדינה מסוימת.
הגבלת מיקום
כדי להגביל את התוצאות לאזור מסוים, צריך להעביר פרמטר locationRestriction.
אפשר גם להגביל את התוצאות לאזור שמוגדר על ידי location ופרמטר radius, על ידי הוספת הפרמטר strictbounds. ההגדרה הזו מנחה את ההשלמה האוטומטית למקומות (מדור קודם) להחזיר רק תוצאות באזור הזה.
פתרון בעיות
יכולות להתרחש הרבה שגיאות, אבל רוב השגיאות שסביר להניח שיתרחשו באפליקציה נגרמות בדרך כלל בגלל שגיאות בהגדרות (לדוגמה, שימוש במפתח API שגוי או הגדרה שגויה של מפתח ה-API) או בגלל שגיאות שקשורות למכסות (האפליקציה חרגה מהמכסה שלה). מידע נוסף על מכסות זמין במאמר מגבלות שימוש.
שגיאות שמתרחשות במהלך השימוש בפקדי ההשלמה האוטומטית מוחזרות ב-method didFailAutocompleteWithError() של פרוטוקולי ה-delegate השונים. המאפיין code של האובייקט NSError שסופק מוגדר לאחד מהערכים של הספירה GMSPlacesErrorCode.