### Install SDKs using CocoaPods Source: https://developers.google.com/maps/documentation/places/ios-sdk/config Install the specified SDKs and their dependencies by running the 'pod install' command in the terminal within your project directory. ```bash cd ``` ```bash pod install ``` -------------------------------- ### Description Property Example Source: https://developers.google.com/maps/documentation/places/ios-sdk/reference/swift/Structs/Place.html Demonstrates how to use the `String(describing:)` initializer with a type conforming to `CustomStringConvertible` to get its textual representation. ```swift struct Point: CustomStringConvertible { let x: Int, y: Int var description: String { return "(\x), y)" } } let p = Point(x: 21, y: 30) let s = String(describing: p) print(s) // Prints "(21, 30)" ``` -------------------------------- ### Fetch Place Details with Combine Source: https://developers.google.com/maps/documentation/places/ios-sdk/combine Use the `fetchPlace` extension to get place details as a Combine publisher. This example demonstrates how to subscribe to the publisher and handle both completion and received values. ```swift GMSPlacesClient.shared() .fetchPlace( id: "placeId", fields: [.placeID, .name, .phoneNumber] ) .sink { completion in print("Completion \(completion)") } receiveValue: { place in print("Got place \(place.name ?? "")") } ``` -------------------------------- ### Custom View Body Implementation Example Source: https://developers.google.com/maps/documentation/places/ios-sdk/reference/swift/Structs/AdvancedPlaceDetailsView.html Provides an example of how to implement the computed `body` property for a custom SwiftUI view. ```swift struct MyView: View { var body: some View { Text("Hello, World!") } } ``` -------------------------------- ### RawRepresentable Usage Examples Source: https://developers.google.com/maps/documentation/places/ios-sdk/reference/swift/Enums/FuelType.html Examples demonstrating how to use raw values with enumerations. ```Swift enum PaperSize: String { case A4, A5, Letter, Legal } print(PaperSize(rawValue: "Legal")) // Prints "Optional(PaperSize.Legal)" print(PaperSize(rawValue: "Tabloid")) // Prints "nil" ``` ```Swift enum PaperSize: String { case A4, A5, Letter, Legal } let selectedSize = PaperSize.Letter print(selectedSize.rawValue) // Prints "Letter" print(selectedSize == PaperSize(rawValue: selectedSize.rawValue)!) // Prints "true" ``` -------------------------------- ### Area Description Example Source: https://developers.google.com/maps/documentation/places/ios-sdk/reference/swift/Structs/Area.html Illustrates how to use the `description` property to get a textual representation of a custom struct conforming to `CustomStringConvertible`. ```swift struct Point: CustomStringConvertible { let x: Int, y: Int var description: String { return "(\(x), \(y))" } } let p = Point(x: 21, y: 30) let s = String(describing: p) print(s) // Prints "(21, 30)" ``` -------------------------------- ### Install CocoaPods Source: https://developers.google.com/maps/documentation/places/ios-sdk/config Install the CocoaPods dependency manager on macOS. This is a prerequisite for managing SDKs using a Podfile. ```bash sudo gem install cocoapods ``` -------------------------------- ### Make an `isOpen` request (Swift) Source: https://developers.google.com/maps/documentation/places/ios-sdk/nearby-search This Swift example demonstrates how to check if a place is open using the `GMSPlacesClient.isOpen` method. It includes error handling and checks for open, closed, or unknown status. ```swift let isOpenRequest = GMSPlaceIsOpenRequest(place: place, date: nil) GMSPlacesClient.shared().isOpen(with: isOpenRequest) { response, error in if let error = error { // Handle Error } switch response.status { case .open: // Handle open case .closed: // Handle closed case .unknown: // Handle unknown } } ``` -------------------------------- ### Get Reviews URL - Swift Source: https://developers.google.com/maps/documentation/places/ios-sdk/reference/objc/Classes/GMSPlaceGoogleMapsLinks.html Returns a URL to show reviews of this place. ```swift var reviewsURL: URL? { get } ``` -------------------------------- ### CustomStringConvertible Description Example Source: https://developers.google.com/maps/documentation/places/ios-sdk/reference/swift/Structs/ConnectorAggregation.html Demonstrates how to implement the `description` property for custom string representation, as required by `CustomStringConvertible`. ```swift struct Point: CustomStringConvertible { let x: Int, y: Int var description: String { return "(\ (x), \ (y))" } } let p = Point(x: 21, y: 30) let s = String(describing: p) print(s) // Prints "(21, 30)" ``` -------------------------------- ### CustomStringConvertible Example Source: https://developers.google.com/maps/documentation/places/ios-sdk/reference/swift/Structs/AccessibilityOptions.html Demonstrates how to implement the CustomStringConvertible protocol to provide a custom textual representation for a type. ```swift struct Point: CustomStringConvertible { let x: Int, y: Int var description: String { return "(\(x), \(y))" } } let p = Point(x: 21, y: 30) let s = String(describing: p) print(s) ``` -------------------------------- ### GMSPlacesAccessNotConfigured Code Source: https://developers.google.com/maps/documentation/places/ios-sdk/reference/objc/Enums/GMSPlacesErrorCode.html The Places API service for iOS is not enabled. Refer to the developer's guide for setup instructions. ```swift case accessNotConfigured = -9 ``` ```objc kGMSPlacesAccessNotConfigured = -9 ``` -------------------------------- ### Run the Places SDK for iOS Sample App Source: https://developers.google.com/maps/documentation/places/ios-sdk/examples Instructions for setting up and running the Places SDK for iOS demo application. This includes downloading the archive, installing dependencies, and configuring API keys. ```bash download the archive navigate to the GooglePlaces directory install dependencies using CocoaPods open the Xcode workspace add your API key to the SDKDemoAPIKey file Build and run the app ``` -------------------------------- ### Running the Places SDK for iOS Demo App Source: https://developers.google.com/maps/documentation/places/ios-sdk/code-samples Instructions for setting up and running the Places SDK for iOS demo application. This includes downloading the sample, installing dependencies, and configuring the API key. ```text Download the archive Navigate to the GooglePlaces directory Install dependencies using CocoaPods Open the Xcode workspace Enable the Places SDK for iOS in your Google Cloud project Obtain an API key and restrict it to the app's bundle identifier Add your API key to the SDKDemoAPIKey file Build and run the app ``` -------------------------------- ### Fetch Autocomplete and Place Details with Places SDK for iOS Source: https://developers.google.com/maps/documentation/places/ios-sdk/migrate-places-sdk This example demonstrates how to initialize the Places client, fetch autocomplete suggestions based on a query and filter, and then retrieve details for the first suggestion using the legacy Places SDK for iOS. Ensure the Places API is enabled and the SDK is initialized with your API key. ```swift // Initialize Places Client. GMSPlacesClient.provideAPIKey(apiKey) let client = GMSPlacesClient.shared() // Fetch Autocomplete Request. let center = CLLocation(latitude: 37.3913916, longitude: -122.0879074) let northEast = CLLocationCoordinate2DMake(37.388162, -122.088137) let southWest = CLLocationCoordinate2DMake(37.395804, -122.077023) let filter = GMSAutocompleteFilter() filter.types = [kGMSPlaceTypeRestaurant] filter.origin = center filter.locationBias = GMSPlaceRectangularLocationOption(northEast, southWest) let request = GMSAutocompleteRequest(query: "Sicilian piz") request.filter = filter client.fetchAutocompleteSuggestions(from: request) { (results, error) in guard let results, error == nil else { print("Autocomplete error: \(String(describing: error))") return } // Fetch Place Request. guard let placeID = results.first?.placeSuggestion?.placeID else { return } let myProperties = [GMSPlaceProperty.name, GMSPlaceProperty.website].map {$0.rawValue} let fetchPlaceRequest = GMSFetchPlaceRequest(placeID: placeID, placeProperties: myProperties, sessionToken: nil) client.fetchPlace(with: fetchPlaceRequest) { (place: GMSPlace?, error: Error?) in guard let place, error == nil else { return } print("Place found: \(String(describing: place.name)); \(String(describing: place.website))") } } ``` -------------------------------- ### Example of CustomStringConvertible Source: https://developers.google.com/maps/documentation/places/ios-sdk/reference/swift/Structs/ContainingPlace.html Demonstrates how to implement the CustomStringConvertible protocol for a custom struct 'Point' to provide a custom textual representation. ```swift struct Point: CustomStringConvertible { let x: Int, y: Int var description: String { return "(\x), \y))" } } let p = Point(x: 21, y: 30) let s = String(describing: p) print(s) ``` -------------------------------- ### Navigate to Swift Demo Directory Source: https://developers.google.com/maps/documentation/places/ios-sdk/code-samples Change directory to the Swift version of the demo app and open the Xcode project. ```bash cd ios-places-sdk-samples/GooglePlaces-Swift/ open GooglePlacesSwiftDemos.xcodeproj ``` -------------------------------- ### Clone the Sample App Repository Source: https://developers.google.com/maps/documentation/places/ios-sdk/code-samples Download the sample code archive from GitHub or clone the repository to your local machine. ```bash git clone https://github.com/googlemaps-samples/ios-places-sdk-samples.git ``` -------------------------------- ### Initialize Places Swift Client and Fetch Autocomplete Suggestions Source: https://developers.google.com/maps/documentation/places/ios-sdk/migrate-places-sdk Initializes the Places Swift Client and demonstrates fetching autocomplete suggestions using the new `AutocompleteRequest` and `async`/`await` pattern. Ensure API key is provided. ```swift // Initialize Places Swift Client. let _ = PlacesClient.provideAPIKey(apiKey) let placesSwiftClient = PlacesClient.shared // Fetch Autocomplete Request. let center = CLLocation(latitude: 37.3913916, longitude: -122.0879074) let northEast = CLLocationCoordinate2DMake(37.388162, -122.088137) let southWest = CLLocationCoordinate2DMake(37.395804, -122.077023) let bias = RectangularCoordinateRegion(northEast: northEast, southWest: southWest) let filter = AutocompleteFilter(types: [ .restaurant ], origin: center, coordinateRegionBias: bias) let autocompleteRequest = AutocompleteRequest(query: "Sicilian piz", filter: filter) let placeID: String switch await placesSwiftClient.fetchAutocompleteSuggestions(with: autocompleteRequest) { case .success(let results): switch results.first { case .place(let placeSuggestion): placeID = placeSuggestion.placeID case .none: fallthrough @unknown default: return } case .failure(let placesError): print("Autocomplete error: \(placesError)") return } ``` -------------------------------- ### Fetch Place Details with Specific Fields Source: https://developers.google.com/maps/documentation/places/ios-sdk/details Example of fetching a place's name and ID. Ensure you specify the desired GMSPlaceField values in your request. ```objective-c // A hotel in Saigon with an attribution. NSString *placeID = @"ChIJV4k8_9UodTERU5KXbkYpSYs"; // Specify the place data types to return. GMSPlaceField fields = (GMSPlaceFieldName | GMSPlaceFieldPlaceID); ``` -------------------------------- ### init(orientation:request:configuration:) Source: https://developers.google.com/maps/documentation/places/ios-sdk/reference/swift/Structs/PlaceSearchView.html Initializes a new PlaceSearchView to display a list of place search results. ```APIDOC ## init(orientation:request:configuration:) ### Description Creates a list of place search results. ### Parameters - **orientation** (PlaceViewOrientation) - Optional - The orientation of the view. - **request** (Binding) - Required - The request for the view, which is used when fetching the place search results. - **configuration** (PlaceSearchConfiguration) - Required - The configuration settings for the view. ### Return Value A view that displays a list of place search results. ``` -------------------------------- ### Fetch Place by ID (Swift) Source: https://developers.google.com/maps/documentation/places/ios-sdk/details Demonstrates how to initialize the PlacesClient and fetch a place by its ID using Swift. It shows how to handle success and failure scenarios. ```APIDOC ## Fetch Place by ID (Swift) ### Description Retrieves a `GMSPlace` object using its unique Place ID and specified fields. Handles the result asynchronously. ### Method `fetchPlace(with: FetchPlaceRequest)` ### Parameters #### Request Body - **placeID** (string) - Required - The unique identifier for the place. - **placeProperties** (array of GMSPlaceField) - Required - Specifies the data types to return (e.g., `.displayName`). ### Request Example ```swift let fetchPlaceRequest = FetchPlaceRequest( placeID: "ChIJV4k8_9UodTERU5KXbkYpSYs", placeProperties: [.displayName] ) ``` ### Response #### Success Response - **place** (`GMSPlace`) - Contains the details of the requested place. #### Response Example ```swift print("The selected place is: \(place.displayName): \(String(describing: place.description))") ``` #### Failure Response - **placesError** (`Error`) - Details of the error if the place could not be fetched. ``` -------------------------------- ### Example of initializing an enum from a raw value Source: https://developers.google.com/maps/documentation/places/ios-sdk/reference/swift/Enums/DayOfWeek.html Demonstrates how to initialize an enum with a raw value and handle cases where the raw value is not valid. ```swift enum PaperSize: String { case A4, A5, Letter, Legal } print(PaperSize(rawValue: "Legal")) // Prints "Optional(PaperSize.Legal)" print(PaperSize(rawValue: "Tabloid")) // Prints "nil" ``` -------------------------------- ### Navigate to SwiftUI Demo Directory Source: https://developers.google.com/maps/documentation/places/ios-sdk/code-samples Change directory to the SwiftUI version of the demo app and open the Xcode project. ```bash cd ios-places-sdk-samples/GooglePlacesDemos/ open GooglePlacesDemos.xcodeproj ``` -------------------------------- ### Example of a long Place ID string Source: https://developers.google.com/maps/documentation/places/ios-sdk/place-id Place IDs can be long strings representing specific locations. This is an example of such an ID. ```text EpID4LC14LC_4LCo4LCv4LGN4LCo4LCX4LCw4LGNIC0g4LC44LGI4LCm4LGN4LCs4LC-4LCm4LGNIOCwsOCxi-CwoeCxjeCwoeCxgSAmIOCwteCwv-CwqOCwr-CxjSDgsKjgsJfgsLDgsY0g4LCu4LGG4LCv4LC_4LCo4LGNIOCwsOCxi-CwoeCxjeCwoeCxgSwg4LC14LC_4LCo4LCv4LGNIOCwqOCwl-CwsOCxjSDgsJXgsL7gsLLgsKjgsYAsIOCwsuCwleCxjeCwt-CxjeCwruCwv-CwqOCwl-CwsOCxjSDgsJXgsL7gsLLgsKjgsYAsIOCwuOCwsOCxguCwsOCxjSDgsKjgsJfgsLDgsY0g4LC14LGG4LC44LGN4LCf4LGNLCDgsLjgsK_gsYDgsKbgsL7gsKzgsL7gsKbgsY0sIOCwueCxiOCwpuCwsOCwvuCwrOCwvuCwpuCxjSwg4LCk4LGG4LCy4LCC4LCX4LC-4LCjIDUwMDA1OSwg4LCt4LC-4LCw4LCk4LCm4LGH4LC24LCCImYiZAoUChIJ31l5uGWYyzsR9zY2qk9lDiASFAoSCd9ZebhlmMs7Efc2NqpPZQ4gGhQKEglDz61OZpjLOxHgDJCFY-o1qBoUChIJi37TW2-YyzsRr_uv50r7tdEiCg1MwFcKFS_dyy4 ``` -------------------------------- ### Get Place Open Status Source: https://developers.google.com/maps/documentation/places/ios-sdk/reference/objc/Classes/GMSPlacesClient.html Gets the open status for a place. It is best practice to check that opening hours are not null before passing in a `GMSPlace`. This method is non-blocking. ```swift func isOpen(with isOpenRequest: GMSPlaceIsOpenRequest, callback: @escaping GMSPlaceOpenStatusResponseCallback) ``` ```objective-c - (void)isOpenWithRequest:(nonnull GMSPlaceIsOpenRequest *)isOpenRequest callback:(nonnull GMSPlaceOpenStatusResponseCallback)callback; ``` -------------------------------- ### Get Place Predictions with Swift Source: https://developers.google.com/maps/documentation/places/ios-sdk/autocomplete Use this Swift code to get autocomplete predictions. It demonstrates creating a session token, setting up an autocomplete filter for place types and location bias, and handling the results or errors from the `findAutocompletePredictions` call. ```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)") } } }) ``` -------------------------------- ### -initWithStatus: Method Source: https://developers.google.com/maps/documentation/places/ios-sdk/reference/objc/Classes/GMSPlaceIsOpenResponse.html Initializes the response with a given status. This is meant to be used for unit testing purposes. ```APIDOC ### -initWithStatus: Initializes the response with a given status. This is meant to be used for unit testing purposes. #### Declaration Swift ``` init(status: GMSPlaceOpenStatus) ``` Objective-C ``` - (nonnull instancetype)initWithStatus:(GMSPlaceOpenStatus)status; ``` ``` -------------------------------- ### Sublocality Property Source: https://developers.google.com/maps/documentation/places/ios-sdk/reference/swift/Structs/PostalAddress.html Sublocality of the address. For example, this can be a neighborhood, borough, or district. ```swift var sublocality: String? { get } ``` -------------------------------- ### Fetch Place by ID (Objective-C) Source: https://developers.google.com/maps/documentation/places/ios-sdk/details Provides an Objective-C example for fetching a place by its ID. It includes specifying the fields and handling the callback with error checking. ```APIDOC ## Fetch Place by ID (Objective-C) ### Description Retrieves a `GMSPlace` object using its unique Place ID and specified fields via a callback. Handles potential errors. ### Method `- (void)fetchPlaceFromPlaceID:(NSString *)placeID placeFields:(GMSPlaceField)fields sessionToken:(nullable GMSAutocompleteSessionToken *)sessionToken callback:(nullable GMSPlaceResultCallback)callback;` ### Parameters #### Path Parameters - **placeID** (NSString) - Required - The unique identifier for the place. #### Query Parameters - **placeFields** (GMSPlaceField) - Required - Specifies the data types to return (e.g., `GMSPlaceFieldName`). - **sessionToken** (GMSAutocompleteSessionToken) - Optional - A session token if the call concludes an autocomplete query; otherwise, `nil`. #### Callback - **place** (`GMSPlace`) - The `GMSPlace` object if found, otherwise `nil`. - **error** (`NSError`) - An error object if the fetch operation fails. ### Request Example ```objectivec NSString *placeID = @"ChIJV4k8_9UodTERU5KXbkYpSYs"; GMSPlaceField fields = (GMSPlaceFieldName | GMSPlaceFieldPlaceID); [_placesClient fetchPlaceFromPlaceID:placeID placeFields:fields sessionToken:nil callback:^(GMSPlace * _Nullable place, NSError * _Nullable error) { // Handle result }]; ``` ### Response #### Success Response - **place** (`GMSPlace`) - Contains the details of the requested place. #### Response Example ```objectivec NSLog(@"The selected place is: %@", [place name]); ``` #### Error Handling - If an error occurs during the fetch operation, the `error` parameter in the callback will be populated. ``` -------------------------------- ### Initialize GMSPlaceEVSearchOptions (Swift) Source: https://developers.google.com/maps/documentation/places/ios-sdk/reference/objc/Classes/GMSPlaceEVSearchOptions.html Swift initializer for GMSPlaceEVSearchOptions, setting the minimum charging rate and preferred connector types. ```swift init(minimumChargingRateKW: Double, connectorTypes: [NSNumber]?) ``` -------------------------------- ### rawValue Property Source: https://developers.google.com/maps/documentation/places/ios-sdk/reference/swift/Enums/RoutingPreference.html Gets the raw integer value of a `RoutingPreference` instance. ```APIDOC ### rawValue The corresponding value of the raw type. A new instance initialized with `rawValue` will be equivalent to this instance. #### Declaration Swift ```swift var rawValue: Int { get } ``` ``` -------------------------------- ### Load Icon Image and Background Color (Swift) Source: https://developers.google.com/maps/documentation/places/ios-sdk/icons Loads an icon image from a URL and sets its background color. This example assumes you have a `place` object with `iconImageUrl` and `iconBackgroundColor` properties. ```swift // Icon image URL let url = URL(string: place.iconImageUrl) DispatchQueue.global().async { guard let url = url, let imageData = try? Data(contentsOf: url) else { print("Could not get image") return } DispatchQueue.main.async { let iconImage = UIImage(data: iconImageData) // Icon image background color let iconBackgroundView = UIView(frame: .zero) iconBackgroundView.backgroundColor = place.iconBackgroundColor // Change icon image color to white let templateImage = iconImage.imageWithRenderingMode(UIImageRenderingModeAlwaysTemplate) imageView.image = templateImage imageView.tintColor = UIColor.white } } ``` -------------------------------- ### init(orientation:request:configuration:) Source: https://developers.google.com/maps/documentation/places/ios-sdk/reference/swift/Structs/AdvancedPlaceSearchView.html Initializes a new instance of AdvancedPlaceSearchView with specified orientation, request, and configuration. ```APIDOC ## Initializer: init(orientation:request:configuration:) Initializes a new instance of `AdvancedPlaceSearchView`. ### Declaration Swift ```swift @MainActor init(orientation: PlaceViewOrientation = .vertical, request: Binding, configuration: AdvancedPlaceSearchConfiguration) ``` ### Parameters - **orientation** (PlaceViewOrientation) - The orientation of the view. - **request** (Binding) - The request for the view, which is used when fetching the place search results. - **configuration** (AdvancedPlaceSearchConfiguration) - The configuration settings for the view. ### Return Value An instance of `AdvancedPlaceSearchView`. ``` -------------------------------- ### SDK Version Source: https://developers.google.com/maps/documentation/places/ios-sdk/reference/objc/Classes/GMSPlacesClient.html Get the current version of the Places SDK for iOS. ```APIDOC ## +SDKVersion ### Description Returns the current version of the Places SDK for iOS as a string. ### Method `+SDKVersion` ### Returns A string representing the SDK version. ``` -------------------------------- ### RawValue Property Usage Source: https://developers.google.com/maps/documentation/places/ios-sdk/reference/swift/Structs/PlaceType.html Example demonstrating how to access the rawValue of an enum and re-initialize it. ```Swift enum PaperSize: String { case A4, A5, Letter, Legal } let selectedSize = PaperSize.Letter print(selectedSize.rawValue) // Prints "Letter" print(selectedSize == PaperSize(rawValue: selectedSize.rawValue)!) // Prints "true" ``` ```Swift let rawValue: String ``` -------------------------------- ### init(maxSize:attributions:authorAttributions:) Source: https://developers.google.com/maps/documentation/places/ios-sdk/reference/swift/Structs/Photo.html Instantiates a Photo object with specified size and attribution information, primarily used for testing purposes. ```APIDOC ## init(maxSize:attributions:authorAttributions:) ### Description Instantiates a Photo with the specified information. This initializer can be used for testing. ### Parameters - **maxSize** (CGSize) - Required - The maximum pixel size in which this photo is available. - **attributions** (NSAttributedString?) - Optional - The data provider attribution string for this photo. - **authorAttributions** ([AuthorAttribution]) - Optional - The optional author attributions for this photo. ### Response A Photo object containing the specified information. ``` -------------------------------- ### Load Icon Image and Background Color (Objective-C) Source: https://developers.google.com/maps/documentation/places/ios-sdk/icons Loads an icon image from a URL and sets its background color in Objective-C. This example assumes you have a `GMSPlace` object with `iconImageUrl` and `iconBackgroundColor` properties. ```objectivec GMSPlace *place; dispatch_async(dispatch_get_global_queue(0, 0), ^{ // Icon image URL NSData * iconImageData = [[NSData alloc] initWithContentsOfURL: [NSURL URLWithString: place.iconImageUrl]]; if (!iconImageData) return; dispatch_async(dispatch_get_main_queue(), ^{ UIImage *iconImage = [UIImage imageWithData:iconImageData]; // Icon image background color UIView *iconBackgroundView = [[UIView alloc] initWithFrame:CGRectZero]; [iconBackgroundView setBackgroundColor:place.iconBackgroundColor]; // Change icon image color to white iconImage = [iconImage imageWithRenderingMode:UIImageRenderingModeAlwaysTemplate]; [imageView setTintColor:[UIColor whiteColor]]; }); }); ``` -------------------------------- ### Routing Parameters Property Source: https://developers.google.com/maps/documentation/places/ios-sdk/reference/swift/Structs/SearchNearbyRequest.html Gets the routing parameters configured for the search request. ```swift var routingParameters: RoutingParameters? { get } ``` -------------------------------- ### Navigate to Archive Demo Directory Source: https://developers.google.com/maps/documentation/places/ios-sdk/code-samples Change directory to the archived version of the demo app and open the Xcode project. ```bash cd ios-places-sdk-samples/Archive/GooglePlaces open GooglePlacesXCFrameworkDemos.xcodeproj ``` -------------------------------- ### -init Source: https://developers.google.com/maps/documentation/places/ios-sdk/reference/objc/Classes/GMSFetchPlaceRequest.html Unavailable. Default init is not available. Please use the designated initializer. ```APIDOC ## -init ### Description Unavailable. Default init is not available. Please use the designated initializer. ### Method Objective-C ``` -------------------------------- ### Get South-West Corner of RectangularCoordinateRegion Source: https://developers.google.com/maps/documentation/places/ios-sdk/reference/swift/Structs/RectangularCoordinateRegion.html Retrieves the south-west corner coordinate of the region. ```swift var southWest: CLLocationCoordinate2D { get } ``` -------------------------------- ### Public Initializer for Testing Source: https://developers.google.com/maps/documentation/places/ios-sdk/reference/swift/Structs/RoutingSummary.html Initializes a `RoutingSummary` instance with legs and an optional directions URL, intended for testing purposes. ```swift init(legs: [Leg], directionsURL: URL?) ``` -------------------------------- ### Get North-East Corner of RectangularCoordinateRegion Source: https://developers.google.com/maps/documentation/places/ios-sdk/reference/swift/Structs/RectangularCoordinateRegion.html Retrieves the north-east corner coordinate of the region. ```swift var northEast: CLLocationCoordinate2D { get } ``` -------------------------------- ### Initializer Source: https://developers.google.com/maps/documentation/places/ios-sdk/reference/swift/Structs/SearchReviewsOptions.html Initializes a new instance of SearchReviewsOptions with optional query and rank preference. ```APIDOC init(query: String? = nil, rankPreference: SearchReviewsRankPreference = .unspecified) Parameters: - query: The query to use when searching through a place’s reviews. - rankPreference: The preferred order of the returned reviews. Defaults to `.unspecified`. ``` -------------------------------- ### Get Text Query (Objective-C) Source: https://developers.google.com/maps/documentation/places/ios-sdk/reference/objc/Classes/GMSPlaceSearchByTextRequest.html Retrieves the text query string for the search. ```objectivec @property (nonatomic, copy, readonly) NSString *_Nonnull textQuery; ``` -------------------------------- ### Get Text Query (Swift) Source: https://developers.google.com/maps/documentation/places/ios-sdk/reference/objc/Classes/GMSPlaceSearchByTextRequest.html Retrieves the text query string for the search. ```swift var textQuery: String { get } ``` -------------------------------- ### Nearby Search Request in Swift (Async/Await) Source: https://developers.google.com/maps/documentation/places/ios-sdk/nearby-search Use this Swift example with async/await to perform a nearby search. It specifies a circular region, desired place properties, and included place types. ```swift let restriction = CircularCoordinateRegion(center: CLLocationCoordinate2DMake(37.7937, -122.3965), radius: 500) let searchNearbyRequest = SearchNearbyRequest( locationRestriction: restriction, placeProperties: [ .name, .coordinate], includedTypes: [ .restaurant, .cafe ] ) switch await placesClient.searchNearby(with: searchNearbyRequest) { case .success(let places): // Handle places case .failure(let placesError): // Handle error } ``` -------------------------------- ### Get Photos URL - Objective-C Source: https://developers.google.com/maps/documentation/places/ios-sdk/reference/objc/Classes/GMSPlaceGoogleMapsLinks.html Returns a URL to show photos of this place. ```objc @property (nonatomic, readonly, nullable) NSURL *photosURL; ``` -------------------------------- ### Initialize SearchReviewsOptions Source: https://developers.google.com/maps/documentation/places/ios-sdk/reference/swift/Structs/SearchReviewsOptions.html Initializes a new SearchReviewsOptions instance with optional query and rank preference. ```swift init(query: String? = nil, rankPreference: SearchReviewsRankPreference = .unspecified) ``` -------------------------------- ### Provide API Key in Swift Source: https://developers.google.com/maps/documentation/places/ios-sdk/config Call this method in your application(_:didFinishLaunchingWithOptions:) to set the API key for the Swift SDK. Replace YOUR_API_KEY with your actual key. ```swift PlacesClient.provideAPIKey("YOUR_API_KEY") ``` -------------------------------- ### Get Photos URL - Swift Source: https://developers.google.com/maps/documentation/places/ios-sdk/reference/objc/Classes/GMSPlaceGoogleMapsLinks.html Returns a URL to show photos of this place. ```swift var photosURL: URL? { get } ``` -------------------------------- ### Get Reviews URL - Objective-C Source: https://developers.google.com/maps/documentation/places/ios-sdk/reference/objc/Classes/GMSPlaceGoogleMapsLinks.html Returns a URL to show reviews of this place. ```objc @property (nonatomic, readonly, nullable) NSURL *reviewsURL; ``` -------------------------------- ### Initialize GMSPlaceEVSearchOptions (Objective-C) Source: https://developers.google.com/maps/documentation/places/ios-sdk/reference/objc/Classes/GMSPlaceEVSearchOptions.html Objective-C initializer for GMSPlaceEVSearchOptions, specifying the minimum charging rate and preferred connector types. ```objc - (nonnull instancetype) initWithMinimumChargingRateKW:(double)minimumChargingRateKW connectorTypes: (nullable NSArray *)connectorTypes; ``` -------------------------------- ### Initializer for PlaceType Source: https://developers.google.com/maps/documentation/places/ios-sdk/reference/swift/Structs/PlaceType.html Demonstrates how to initialize a `PlaceType` using its raw value. ```APIDOC ## Initializer for PlaceType ### Description Creates a new instance with the specified raw value. If there is no value of the type that corresponds with the specified raw value, this initializer returns `nil`. ### Declaration Swift ```swift init(rawValue: String) ``` ### Parameters - **_rawValue** (String) - The raw value to use for the new instance. ### Example ```swift enum PaperSize: String { case A4, A5, Letter, Legal } print(PaperSize(rawValue: "Legal")) // Prints "Optional(PaperSize.Legal)" print(PaperSize(rawValue: "Tabloid")) // Prints "nil" ``` ``` -------------------------------- ### Provide API Key in Objective-C Source: https://developers.google.com/maps/documentation/places/ios-sdk/config Call this method in your application:didFinishLaunchingWithOptions: to set the API key for the Objective-C SDK. Replace YOUR_API_KEY with your actual key. ```objectivec [GMSPlacesClient provideAPIKey:@"YOUR_API_KEY"]; ``` -------------------------------- ### GMSAutocompleteFetcher Autocomplete Filter Source: https://developers.google.com/maps/documentation/places/ios-sdk/reference/objc/Classes/GMSAutocompleteFetcher Gets or sets the filter to apply to autocomplete suggestions. ```APIDOC ## autocompleteFilter ### Description Filter to apply to autocomplete suggestions (can be nil). ### Parameters #### Path Parameters - **autocompleteFilter** (GMSAutocompleteFilter *) - Optional - The filter to apply to autocomplete suggestions. ### Response Example ``` { "example": "var autocompleteFilter: GMSAutocompleteFilter? { get set }" } ``` ``` -------------------------------- ### Provide API Key for GooglePlaces Source: https://developers.google.com/maps/documentation/places/ios-sdk/start Call this method in your application(_:didFinishLaunchingWithOptions:) to provide your API key for the Google Places SDK. Replace YOUR_API_KEY with your actual key. ```swift GMSPlacesClient.provideAPIKey("YOUR_API_KEY") ``` -------------------------------- ### PriceRange Price Properties Source: https://developers.google.com/maps/documentation/places/ios-sdk/reference/swift/Structs/PriceRange.html Accessors for the start and end price values of a range. ```Swift var endPrice: Money? { get } ``` ```Swift var startPrice: Money? { get } ``` -------------------------------- ### GMSPlaceEVSearchOptions Initialization Source: https://developers.google.com/maps/documentation/places/ios-sdk/reference/objc/Classes/GMSPlaceEVSearchOptions.html Details on how to initialize the GMSPlaceEVSearchOptions object with specific charging requirements. ```APIDOC ## -initWithMinimumChargingRateKW:connectorTypes: ### Description Initializes a new instance of GMSPlaceEVSearchOptions with specified charging rate and connector types. ### Parameters - **minimumChargingRateKW** (double) - Required - The minimum charging rate of the EV charging connector in kilowatts. - **connectorTypes** (NSArray *) - Optional - The list of preferred EV connector types. ### Request Example // Objective-C [[GMSPlaceEVSearchOptions alloc] initWithMinimumChargingRateKW:50.0 connectorTypes:@[@1, @2]]; ``` -------------------------------- ### Get SDK Version Source: https://developers.google.com/maps/documentation/places/ios-sdk/reference/objc/Classes/GMSPlacesClient.html Returns the version for this release of the Google Places SDK for iOS. ```Objective-C + (nonnull NSString *)SDKVersion; ``` -------------------------------- ### Configure API Keys using xcconfig Source: https://developers.google.com/maps/documentation/places/ios-sdk/code-samples Create a local configuration file to store your Places API and Maps API keys. ```text PLACES_API_KEY = YOUR_PLACES_API_KEY MAPS_API_KEY = YOUR_MAPS_API_KEY ``` -------------------------------- ### SDK Long Version Source: https://developers.google.com/maps/documentation/places/ios-sdk/reference/objc/Classes/GMSPlacesClient.html Get the detailed version information of the Places SDK for iOS. ```APIDOC ## +SDKLongVersion ### Description Returns the detailed version information of the Places SDK for iOS as a string. ### Method `+SDKLongVersion` ### Returns A string representing the detailed SDK version. ``` -------------------------------- ### DistanceMeters Property - Objective-C Source: https://developers.google.com/maps/documentation/places/ios-sdk/reference/objc/Classes/GMSPlaceLeg.html Get the distance of this leg of the trip in meters using Objective-C. ```Objective-C @property (nonatomic, readonly) NSUInteger distanceMeters; ``` -------------------------------- ### init(placeID:placeProperties:sessionToken:) Source: https://developers.google.com/maps/documentation/places/ios-sdk/reference/swift/Structs/FetchPlaceRequest.html Initializes a new FetchPlaceRequest object to be used with PlacesClient to fetch specific place details. ```APIDOC ## init(placeID:placeProperties:sessionToken:) ### Description Initializes a request object to fetch details for a specific place using its ID and requested properties. ### Parameters #### Request Body - **placeID** (String) - Required - The ID of the place to be requested. - **placeProperties** ([PlaceProperty]) - Required - The properties of the place to be requested. Must not be empty. - **sessionToken** (AutocompleteSessionToken?) - Optional - The session token to associate the request with a billing session. ### Request Example { "placeID": "ChIJN1t_tDeuEmsRUsoyG83frY4", "placeProperties": ["name", "formattedAddress"], "sessionToken": "session_token_string" } ``` -------------------------------- ### Fetch Place Details and then a Photo (Swift) Source: https://developers.google.com/maps/documentation/places/ios-sdk/place-photos This snippet demonstrates fetching place details first, then using the retrieved place object to get the first available photo. Ensure you handle potential errors and cases where a place might not have photos. ```swift // First fetch place details // A hotel in Saigon with an attribution. let placeID = "ChIJV4k8_9UodTERU5KXbkYpSYs" let fetchPlaceRequest = FetchPlaceRequest( placeID: placeID, placeProperties: [ . name, .website ] ) var fetchedPlace: Place switch await placesClient.fetchPlace(with: fetchPlaceRequest) { case .success(let place): fetchedPlace = place case .failure(let placesError): // Handle error } // Use the place details to fetch a photo's image. guard let photo = fetchedPlace.photos?.first else { // Handle place without photos. } let fetchPhotoRequest = FetchPhotoRequest(photo: photo, maxSize: CGSizeMake(4800, 4800)) switch await placesClient.fetchPhoto(with: fetchPhotoRequest) { case .success(let uiImage): // Handle image. case .failure(let placesError): // Handle error } ``` -------------------------------- ### DistanceMeters Property - Swift Source: https://developers.google.com/maps/documentation/places/ios-sdk/reference/objc/Classes/GMSPlaceLeg.html Get the distance of this leg of the trip in meters using Swift. ```Swift var distanceMeters: UInt { get } ``` -------------------------------- ### Text Search Request with Callback in Objective-C Source: https://developers.google.com/maps/documentation/places/ios-sdk/text-search This Objective-C example demonstrates how to initialize a `GMSPlaceSearchByTextRequest` with a text query and place properties. It configures parameters such as `isOpenNow`, `includedType`, `maxResultCount`, `minRating`, `rankPreference`, `isStrictTypeFiltering`, `priceLevels`, and `locationBias`. The response is handled via a callback block. ```objectivec // Create the GMSPlaceSearchByTextRequest object. GMSPlaceSearchByTextRequest *request = [[GMSPlaceSearchByTextRequest alloc] initWithTextQuery:@"pizza in New York" placeProperties:@[GMSPlacePropertyName, GMSPlacePropertyPlaceID]]; request.isOpenNow = YES; request.includedType = @"restaurant"; request.maxResultCount = 5; request.minRating = 3.5; request.rankPreference = GMSPlaceSearchByTextRankPreferenceDistance; request.isStrictTypeFiltering = YES; request.priceLevels = @[ @(kGMSPlacesPriceLevelFree), @(kGMSPlacesPriceLevelCheap) ]; request.locationBias = GMSPlaceCircularLocationOption(CLLocationCoordinate2DMake(40.7, -74.0), 200.0); // Array to hold the places in the response _placeResults = [NSArray array]; // Create the GMSPlaceSearchByTextRequest object. [_placesClient searchByTextWithRequest:request callback:^(NSArray *_Nullable placeResults, NSError * _Nullable error) { if (error != nil) { NSLog(@"An error occurred %@", [error localizedDescription]); return; } else { if (placeResults.count > 0) { // Get list of places. _placeResults = placeResults; } } } ]; ``` -------------------------------- ### Duration Property - Objective-C Source: https://developers.google.com/maps/documentation/places/ios-sdk/reference/objc/Classes/GMSPlaceLeg.html Get the time it takes to complete this leg of the trip in Objective-C. ```Objective-C @property (nonatomic, readonly) NSTimeInterval duration; ``` -------------------------------- ### Initialize GMSPlaceSearchByTextRequest with Text Query and Place Properties (Objective-C) Source: https://developers.google.com/maps/documentation/places/ios-sdk/reference/objc/Classes/GMSPlaceSearchByTextRequest.html Use this initializer to create a new text search request. Specify the search query and the desired place properties to be returned. Ensure the placeProperties array is not empty to avoid errors. ```objectivec - (nonnull instancetype)initWithTextQuery:(nonnull NSString *)textQuery placeProperties: (nonnull NSArray *)placeProperties; ``` -------------------------------- ### Duration Property - Swift Source: https://developers.google.com/maps/documentation/places/ios-sdk/reference/objc/Classes/GMSPlaceLeg.html Get the time it takes to complete this leg of the trip in Swift. ```Swift var duration: TimeInterval { get } ``` -------------------------------- ### Get Write Review URL - Objective-C Source: https://developers.google.com/maps/documentation/places/ios-sdk/reference/objc/Classes/GMSPlaceGoogleMapsLinks.html Returns a URL to write a review for this place. ```objc @property (nonatomic, readonly, nullable) NSURL *writeAReviewURL; ``` -------------------------------- ### Fetch and Display First Place Photo (Objective-C) Source: https://developers.google.com/maps/documentation/places/ios-sdk/photos This Objective-C snippet demonstrates fetching the first photo for a given place ID. It includes error handling for both fetching the place and loading the photo, and displays the image and attributions. Make sure `_placesClient`, `imageView`, and `lblText` are properly initialized. ```objectivec // Specify the place data types to return (in this case, just photos). GMSPlaceField fields = (GMSPlaceFieldPhotos); NSString *placeId = @"INSERT_PLACE_ID_HERE"; [_placesClient fetchPlaceFromPlaceID:placeId placeFields:fields sessionToken:nil callback:^(GMSPlace * _Nullable place, NSError * _Nullable error) { if (error != nil) { NSLog(@"An error occurred %@", [error localizedDescription]); return; } if (place != nil) { GMSPlacePhotoMetadata *photoMetadata = [place photos][0]; [self->_placesClient loadPlacePhoto:photoMetadata callback:^(UIImage * _Nullable photo, NSError * _Nullable error) { if (error != nil) { NSLog(@"Error loading photo metadata: %@", [error localizedDescription]); return; } else { // Display the first image and its attributions. self->imageView.image = photo; self->lblText.attributedText = photoMetadata.attributions; } }]; } }]; ``` -------------------------------- ### Get Write Review URL - Swift Source: https://developers.google.com/maps/documentation/places/ios-sdk/reference/objc/Classes/GMSPlaceGoogleMapsLinks.html Returns a URL to write a review for this place. ```swift var writeAReviewURL: URL? { get } ``` -------------------------------- ### Initialize AutocompleteUICustomization Source: https://developers.google.com/maps/documentation/places/ios-sdk/reference/swift/Structs/AutocompleteUICustomization.html Creates a new instance of AutocompleteUICustomization with optional parameters for list density, icons, and theme. ```Swift init(listDensity: AutocompleteListDensity = .twoLine, listItemIcon: AutocompleteUIIcon = .defaultIcon, theme: PlacesMaterialTheme = PlacesMaterialTheme()) ``` -------------------------------- ### Fetch place reviews and data in Swift Source: https://developers.google.com/maps/documentation/places/ios-sdk/attributions This Swift snippet demonstrates how to fetch a place by its ID, specifying that you need the name, website, and reviews. It includes error handling and accessing the first review. ```swift // Define a Place ID. let placeID = "ChIJV4k8_9UodTERU5KXbkYpSYs" // Specify the place data types to return. let myProperties: [GMSPlaceProperty] = [.name, .website, .reviews] // Create the GMSFetchPlaceRequest object. let fetchPlaceRequest = GMSFetchPlaceRequest(placeID: placeID, placeProperties: myProperties) client.fetchPlaceWithRequest(fetchPlaceRequest: fetchPlaceRequest, callback: { (place: GMSPlace?, error: Error?) in if let error = error { print("An error occurred: \(error.localizedDescription)") return } if let place = place { let firstReview: GMSPlaceReview = place.reviews![0] // Use firstReview to access review text, authorAttribution, and other fields. } }) ``` -------------------------------- ### Get Place URL - Objective-C Source: https://developers.google.com/maps/documentation/places/ios-sdk/reference/objc/Classes/GMSPlaceGoogleMapsLinks.html Returns a URL to show this place in Google Maps. ```objc @property (nonatomic, readonly, nullable) NSURL *placeURL; ``` -------------------------------- ### Fetch Place Details with Callback in Swift Source: https://developers.google.com/maps/documentation/places/ios-sdk/details-place This Swift example demonstrates fetching place details using a callback. It specifies the place ID and desired properties, then processes the `GMSPlace` object or error in the callback. ```swift // A hotel in Saigon with an attribution. let placeID = "ChIJV4k8_9UodTERU5KXbkYpSYs" // Specify the place data types to return. let myProperties = [GMSPlaceProperty.name, GMSPlaceProperty.website].map {$0.rawValue} // Create the GMSFetchPlaceRequest object. let fetchPlaceRequest = GMSFetchPlaceRequest(placeID: placeID, placeProperties: myProperties, sessionToken: nil) client.fetchPlace(with: fetchPlaceRequest, callback: { (place: GMSPlace?, error: Error?) in guard let place, error == nil else { return } print("Place found: \(String(describing: place.name))") }) ``` -------------------------------- ### Get Place URL - Swift Source: https://developers.google.com/maps/documentation/places/ios-sdk/reference/objc/Classes/GMSPlaceGoogleMapsLinks.html Returns a URL to show this place in Google Maps. ```swift var placeURL: URL? { get } ``` -------------------------------- ### FetchPhotoRequest Initialization Source: https://developers.google.com/maps/documentation/places/ios-sdk/reference/swift/Structs/FetchPhotoRequest.html Initializes a FetchPhotoRequest to fetch a photo with specified size constraints using the PlacesClient. ```APIDOC ## init(photo:maxSize:) ### Description Initializes a `FetchPhotoRequest` object to be used with `PlacesClient` to fetch a photo. The photo will be returned in its original size if it's smaller than the specified `maxSize`. If the photo is larger than `maxSize` in either dimension, it will be scaled down to match the smaller of the two dimensions while maintaining its original aspect ratio. The height and width of `maxSize` must be integers between 1 and 4800, inclusive. Requests with dimensions outside this range will result in an error returned in the `PlacesClient` callback. ### Method `init(photo: Photo, maxSize: CGSize)` ### Parameters #### Path Parameters None #### Query Parameters None #### Request Body None ### Request Example ```swift let photoRequest = FetchPhotoRequest(photo: selectedPhoto, maxSize: CGSize(width: 300, height: 200)) ``` ### Response #### Success Response (200) N/A - This is an initializer, not an endpoint that returns data directly. #### Response Example N/A ``` -------------------------------- ### Accessing the offset property Source: https://developers.google.com/maps/documentation/places/ios-sdk/reference/objc/Classes/GMSAutocompleteMatchFragment Retrieves the starting index of the matched fragment within the string. ```Swift var offset: UInt { get } ``` ```Objective-C @property (nonatomic, readonly) NSUInteger offset; ``` -------------------------------- ### init Source: https://developers.google.com/maps/documentation/places/ios-sdk/reference/objc/Classes/GMSAutocompleteTableDataSource.html Initializes a data source. This method is deprecated. ```APIDOC ## init **Deprecated** Use Places Swift SDK’s (https://developers.google.com/maps/documentation/places/ios-sdk/google-places-swift) placeAutocomplete API instead. Initializes a data source. #### Declaration ```swift init() ``` ```objectivec - (nonnull instancetype)init; ``` ``` -------------------------------- ### NeighborhoodSummary Disclosure Text Language Code Property Source: https://developers.google.com/maps/documentation/places/ios-sdk/reference/swift/Structs/NeighborhoodSummary.html Gets the language code for the disclosure text. ```swift var disclosureTextLanguageCode: String? { get } ``` -------------------------------- ### Fetch Place Details with Callback in Objective-C Source: https://developers.google.com/maps/documentation/places/ios-sdk/details-place This Objective-C example shows how to fetch place details using a callback. It initializes `GMSFetchPlaceRequest` with a place ID and properties, then handles the `GMSPlace` object or error in the completion block. ```objective-c // A hotel in Saigon with an attribution. NSString *placeID = @"ChIJV4k8_9UodTERU5KXbkYpSYs"; // Specify the place data types to return. NSArray *myProperties = @[GMSPlacePropertyName, GMSPlacePropertyWebsite]; // Create the GMSFetchPlaceRequest object. GMSFetchPlaceRequest *fetchPlaceRequest = [[GMSFetchPlaceRequest alloc] initWithPlaceID:placeID placeProperties: myProperties sessionToken:nil]; [placesClient fetchPlaceWithRequest: fetchPlaceRequest callback: ^(GMSPlace *_Nullable place, NSError *_Nullable error) { if (error != nil) { NSLog(@"An error occurred %@", [error localizedDescription]); return; } else { NSLog(@"Place Found: %@", place.name); NSLog(@"The place URL: %@", place.website); } }]; ``` -------------------------------- ### -lookUpPlaceID:callback: Source: https://developers.google.com/maps/documentation/places/ios-sdk/reference/objc/Classes/GMSPlacesClient.html Deprecated. Replaced by `fetchPlaceWithRequest:callback:`. Gets details for a place. This method is non-blocking. ```APIDOC ## -lookUpPlaceID:callback: ### Description Deprecated This method is replaced by `fetchPlaceWithRequest:callback:` and will be removed in a future release. Get details for a place. This method is non-blocking. ### Declaration Objective-C ```objc - (void)lookUpPlaceID:(nonnull NSString *)placeID callback:(nonnull GMSPlaceResultCallback)callback; ``` ### Parameters - **placeID** (String) - The place ID to look up. - **callback** (GMSPlaceResultCallback) - The callback to invoke with the lookup result. ```