您可以使用 Places SDK for iOS 要求在應用程式中顯示地點相片。相片服務傳回的相片取自各種來源,包括業主和使用者提供的相片。如要擷取地點的相片,請按照下列步驟操作:
- 呼叫
[GMSPlacesClient fetchPlaceFromPlaceId]
,並傳遞包含地點 ID 和回呼的字串。這會使用GMSPlacePhotoMetadataList
物件呼叫回呼。 - 在
GMSPlacePhotoMetadataList
物件上,存取results
屬性,並從陣列中選取要載入的相片。 - 對從這份清單載入的每個
GMSPlacePhotoMetadata
呼叫[GMSPlacesClient loadPlacePhoto:callback:]
或[GMSPlacesClient loadPlacePhoto:constrainedToSize:scale:callback:]
。這些物件會使用可用的 UIImage 呼叫回呼。相片的寬度或高度上限為 1600 像素
程式碼範例
以下範例方法會採用地點 ID,並取得傳回清單中的第一張相片。您可以使用此方法做為在自有應用程式中建立方法的範本。
Swift
// Specify the place data types to return (in this case, just photos). let fields: GMSPlaceField = GMSPlaceField(rawValue: UInt(GMSPlaceField.photos.rawValue))! placesClient?.fetchPlace(fromPlaceID: "INSERT_PLACE_ID_HERE", placeFields: fields, sessionToken: nil, callback: { (place: GMSPlace?, error: Error?) in if let error = error { print("An error occurred: \(error.localizedDescription)") return } if let place = place { // Get the metadata for the first photo in the place photo metadata list. let photoMetadata: GMSPlacePhotoMetadata = place.photos![0] // Call loadPlacePhoto to display the bitmap and attribution. self.placesClient?.loadPlacePhoto(photoMetadata, callback: { (photo, error) -> Void in if let error = error { // TODO: Handle the error. print("Error loading photo metadata: \(error.localizedDescription)") return } else { // Display the first image and its attributions. self.imageView?.image = photo; self.lblText?.attributedText = photoMetadata.attributions; } }) } })
Objective-C
// 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; } }]; } }];
快取
使用 [GMSPlacesClient loadPlacePhoto:callback:]
或 [GMSPlacesClient loadPlacePhoto:constrainedToSize:scale:callback:]
載入的相片會由共用 NSURLCache
中的 基礎網址載入系統在磁碟和記憶體內快取。
如要設定快取行為,您可以在應用程式委派的 application:didFinishLaunchingWithOptions:
方法中使用 [NSURLCache setSharedURLCache:]
變更共用網址快取。
如果您不希望應用程式與 Places SDK for iOS 共用 NSURLCache
,可以建立新的 NSURLCache
,然後在應用程式中單獨使用這項資訊,而不必將其設為共用快取。
歸因
在大多數情況下,使用地點相片時可以不用加上作者資訊,圖片本身也可能已加入必要的作者資訊。不過,如果傳回的 GMSPlacePhotoMetadata
例項包含作者資訊,您每次顯示圖片時就必須在應用程式中另外加入作者資訊。請注意,作者資訊中的連結必須可供輕觸。請參閱作者資訊說明文件。
用量限制
擷取圖片需要一單位配額;擷取相片中繼資料沒有用量限制。進一步瞭解用量與計費。