Place Autocomplete

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

Add an autocomplete UI control

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

You can add the autocomplete UI control to your app in the following ways:

Add a full-screen control

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

To add a full-screen control to your app:

Create a UI element in your main app to launch the autocomplete UI control,
for example a touch handler on a UIButton.

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

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;

Add a search bar using popover results

The following code example shows placing a search bar on the right side of the
navigation bar, and displaying results in a popover.

Caution:
Popovers will only appear on iPad, and on the iPhone 6+ in landscape mode. On
all other devices this will fallback to a fullscreen view controller.

Note: The UISearchDisplayController API does not support the concept of
asynchronous data updates, so it is necessary to force table updates by
reloading table data in the didUpdateAutocompletePredictions and
didRequestAutocompletePredictions methods of the
GMSAutoCompleteResultsDelegate protocol.

Customize text and background colors

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

By using the native iOS UIAppearance protocol to globally style UI controls where possible. These settings apply to many, but not all, of the UI control
elements.

By using the SDK methods on the widget classes to set properties which
are not supported by the UIAppearance protocol.

Typically, your app will use some combination of the UIAppearance protocol
and the SDK methods. The following diagram shows which elements can be styled:

The following table lists all of the UI elements, and indicates how each
one should be styled (UIAppearance protocol or SDK method).

UI Element

Method

How to style

Navigation Bar tint (background)

UIAppearance protocol

Call setBarTintColor on UINavigationBar proxy.

Navigation Bar tint color (search bar text caret and Cancel button)

UIAppearance protocol

Call setTintColor on UINavigationBar proxy.

Search Bar text color

UIAppearance protocol

Set NSForegroundColorAttributeName in searchBarTextAttributes.

Search bar tint color

N/A

The search bar is translucent, and will display as a shaded version
of the Navigation Bar.

Search bar placeholder text color (default search text)

UIAppearance protocol

Set NSForegroundColorAttributeName in placeholderAttributes.

Primary text (also applied to error and message text)

SDK method

Call primaryTextColor.

Primary text highlight

SDK method

Call primaryTextHighlightColor.

Secondary text

SDK method

Call secondaryTextColor.

Error and message text

SDK method

Call primaryTextColor.

Table cell background

SDK method

Call tableCellBackgroundColor.

Table cell separator color

SDK method

Call tableCellSeparatorColor.

"Try Again" button

SDK method

Call tintColor.

Activity indicator (progress spinner)

UIAppearance protocol

Call setColor on UIActivityIndicatorView proxy.

"Powered by Google" logo, Sad cloud image

N/A

White or gray version is automatically selected based on background contrast.

Magnifying glass and clear text icons in Search Bar text field

N/A

To style, replace the default images with images of the desired color.

Note: These properties only affect the color settings of UI elements. Changing
the size of UI elements, or the font used in table cells, is not supported.

Use the UIAppearance protocol

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

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

Set UI control style properties

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

Note: For GMSAutocompleteViewController and GMSAutocompleteResultsViewController,
you can use Interface Builder to set these values.

Get place predictions programmatically

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

A GMSCoordinateBounds
object biasing the results to a specific area specified by latitude and
longitude bounds.

A GMSAutocompleteSessionToken,
which is used to identify each individual session. Your app should
pass the same token for each autocomplete request call, then pass that token,
along with a Place ID, in the subsequent call to fetchPlacefromPlaceID:
to retrieve Place Details for the place that was selected by the user.

attributedFullText – The full text of the prediction, in the form of
an NSAttributedString. For example, 'Sydney Opera House, Sydney, New South
Wales, Australia'. Every text range that matches the user input has an
attribute, kGMSAutocompleteMatchAttribute. You can use this attribute to
highlight the matching text in the user's query, for example, as shown below.

placeID – The place ID of the predicted place. A place ID is a
textual identifier that uniquely identifies a place. For more information about
place IDs, see the Place ID overview.

The following code example illustrates how to highlight in bold text the parts
of the result that match text in the user's query, using enumerateAttribute:

Use the fetcher

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

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

Session tokens

Session tokens group the query and selection phases of a user autocomplete
search into a discrete session for billing purposes. The session begins when
the user starts typing a query, and concludes when they select a place. Each
session can have multiple queries, followed by one place selection. Once a
session has concluded, the token is no longer valid; your app must generate a
fresh token for each session. We recommend using session tokens for all
programmatic autocomplete sessions (when you use the full-screen controller,
or the results controller, the API takes care of this automatically).

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

Set the GMSCoordinateBounds of autocomplete

You can supply a GMSCoordinateBounds to autocomplete to guide the
supplied completions. For example, if you already have a Google Map in your
view controller, you can use the bounds of the current viewport to bias
autocomplete results.

Controlling the network activity indicator

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

For GMSAutocompleteViewController you must implement the delegate methods didRequestAutocompletePredictions: and didUpdateAutocompletePredictions:.

For GMSAutocompleteResultsViewController you must implement the delegate methods didRequestAutocompletePredictionsForResultsController: and didUpdateAutocompletePredictionsForResultsController:.

For GMSAutocompleteTableDataSource you must implement the delegate methods didRequestAutocompletePredictionsForTableDataSource: and didUpdateAutocompletePredictionsForTableDataSource:.

By implementing these methods and setting [UIApplication sharedApplication].networkActivityIndicatorVisible
to YES and NO respectively the status bar will correctly match the
autocomplete UI.

Troubleshooting

Although a wide variety of errors can occur, the majority of the errors your
app is likely to experience are usually caused by configuration errors (for
example, the wrong API key was used, or the API key was configured
incorrectly), or quota errors (your app has exceeded its quota). See
Usage Limits for more information about quotas.

Errors that occur in the use of the autocomplete controls are returned in the
didFailAutocompleteWithError() method of the various delegate protocols. The
code property of the supplied NSError object is set to one of the values of
the GMSPlacesErrorCode enumeration.