您可以使用 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
執行個體包含出處,您必須在顯示圖片的任何位置,在應用程式中加入額外的出處。請注意,歸因中的連結必須可供輕觸。請參閱歸因說明文件。
用量限制
擷取映像檔的配額為一個單位;擷取相片中繼資料沒有用量限制。進一步瞭解用量與計費。