Text Search (新版)

歐洲經濟區 (EEA) 開發人員

Text Search (新版) 可根據字串 (例如「台南魯肉飯」、「西門町附近的鞋店」或「中正路 123 號」),傳回一組地點的相關資訊。這項服務會傳回與文字字串及位置自訂調整設定相符的地點清單。

除了必要參數外,Text Search (新版) 也支援使用選用參數調整查詢,以取得更符合需求的結果。

透過 Text Search 取得 Places 清單

呼叫 GMSPlacesClient searchByTextWithRequest: 提出 Text Search 要求,並傳遞定義要求參數的 GMSPlaceSearchByTextRequest 物件,以及 GMSPlaceSearchByTextResultCallback 類型的回呼方法,以處理回應。

GMSPlaceSearchByTextRequest 物件會指定要求的所有必要和選用參數。必要參數包括:

  • GMSPlace 物件中要傳回的欄位清單,也稱為「欄位遮罩」,由 GMSPlaceProperty 定義。如果您未在欄位清單中指定至少一個欄位,或省略欄位清單,呼叫就會傳回錯誤。
  • 文字查詢。

這個 Text Search 要求範例指定回應 GMSPlace 物件,包含搜尋結果中每個 GMSPlace 物件的地點名稱和地點 ID。此外,系統也會篩選回應,只傳回「餐廳」類型的地點。

Places Swift SDK

let restriction = GMSPlaceRectangularLocationOption(
      northEast: CLLocationCoordinate2D(latitude: 20, longitude: 30),
      southWest: CLLocationCoordinate2D(latitude: 40, longitude: 50)
)
let searchByTextRequest = SearchByTextRequest(
        textQuery: "pizza in New York",
        placeProperties: [ .name, .placeID ],
        locationRestriction: restriction,
        includedType: .restaurant,
        maxResultCount: 5,
        minRating: 3.5,
        priceLevels: [ .moderate, .inexpensive ],
        isStrictTypeFiltering: true
)
switch await placesClient.searchByText(with: searchByTextRequest) {
case .success(let places):
  // Handle places
case .failure(let placesError):
  // Handle error
}

Swift

// Create the GMSPlaceSearchByTextRequest object.
let myProperties = [GMSPlaceProperty.name, GMSPlaceProperty.placeID].map {$0.rawValue}
let request = GMSPlaceSearchByTextRequest(textQuery:"pizza in New York", placeProperties:myProperties)
request.isOpenNow = true
request.includedType = "restaurant"
request.maxResultCount = 5
request.minRating = 3.5
request.rankPreference = .distance
request.isStrictTypeFiltering = true
request.locationBias =  GMSPlaceCircularLocationOption(CLLocationCoordinate2DMake(40.7, -74.0), 200.0)

// Array to hold the places in the response
var placeResults: [GMSPlace] = []

let callback: GMSPlaceSearchByTextResultCallback = { [weak self] results, error in
  guard let self, error == nil else {
    if let error {
      print(error.localizedDescription)
    }
    return
  }
  guard let results = results as? [GMSPlace] else {
    return
  }
  placeResults = results
}

GMSPlacesClient.shared().searchByText(with: request, callback: callback)

Objective-C

// 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<GMSPlace *> *_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;
      }
    }
  }
];

Text Search 回應

Text Search API 會以 GMSPlace 物件的形式傳回相符項目陣列,每個相符地點都有一個 GMSPlace 物件。

取得營業狀態

GMSPlacesClient 物件包含名為 isOpenWithRequest 的成員函式 (Swift 為 isOpenRequest,GooglePlacesSwift 為 isPlaceOpenRequest),可根據函式呼叫中指定的時間,傳回表示地點目前是否營業的回應。

這個方法會採用 GMSPlaceIsOpenWithRequest 類型的單一引數,其中包含:

  • GMSPlace 物件或指定地點 ID 的字串。如要進一步瞭解如何建立包含必要欄位的 Place 物件,請參閱「Place Details」。
  • 選用的 NSDate (Obj-C) 或 Date (Swift) 物件,用於指定要檢查的時間。如未指定時間,則預設為目前時間。
  • GMSPlaceOpenStatusResponseCallback 方法,用於處理回應。
  • >

GMSPlaceIsOpenWithRequest 方法需要在 GMSPlace 物件中設定下列欄位:

  • GMSPlacePropertyUTCOffsetMinutes
  • GMSPlacePropertyBusinessStatus
  • GMSPlacePropertyOpeningHours
  • GMSPlacePropertyCurrentOpeningHours
  • GMSPlacePropertySecondaryOpeningHours

如果 Place 物件未提供這些欄位,或您傳遞了地點 ID,這個方法會使用 GMSPlacesClient GMSFetchPlaceRequest: 擷取這些欄位。

isOpenWithRequest 則回應

isOpenWithRequest 會傳回 GMSPlaceIsOpenResponse 物件,其中包含名為 status 的布林值,指出商家是否營業、停業或狀態不明。

語言 開啟時的值 關閉時的值 狀態不明時的值
Places Swift true false nil
Swift .open .closed .unknown
Objective-C GMSPlaceOpenStatusOpen GMSPlaceOpenStatusClosed GMSPlaceOpenStatusUnknown

「isOpenWithRequest」的帳單

  • GMSPlacePropertyUTCOffsetMinutes 和 GMSPlacePropertyBusinessStatus 欄位會依 Basic Data SKU 計費。其餘營業時間則依 Place Details Enterprise SKU 計費。
  • 如果 GMSPlace 物件已包含先前要求傳回的這些欄位,系統不會再次收費。

範例:提出 GMSPlaceIsOpenWithRequest 要求

以下範例說明如何在現有的 GMSPlace 物件中初始化 GMSPlaceIsOpenWithRequest。

Places Swift SDK

        let isOpenRequest = IsPlaceOpenRequest(place: place)
        switch await placesClient.isPlaceOpen(with: isOpenRequest) {
          case .success(let isOpenResponse):
            switch isOpenResponse.status {
              case true:
                // Handle open
              case false:
                // Handle closed
              case nil:
                // Handle unknown
          case .failure(let placesError):
            // Handle error
        }
        

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
        }
      }
        

Objective-C

          GMSPlaceIsOpenRequest *isOpenRequest = [[GMSPlaceIsOpenRequest alloc] initWithPlace:place date:nil];

          [[GMSPlacesClient sharedClient] isOpenWithRequest:isOpenRequest callback:^(GMSPlaceIsOpenResponse response, NSError *_Nullable error) {
            if (error) {
              // Handle error
            }

            switch (response.status) {
              case GMSPlaceOpenStatusOpen:
                // Handle open
              case GMSPlaceOpenStatusClosed:
                // Handle closed
              case GMSPlaceOpenStatusUnknown:
                // Handle unknown
            }
          }];
          

分頁

Text Search 提供分頁物件,即 hasNextPage 布林值,會在 Text Search 呼叫的第一個回應中傳回。如果有下一頁,您可以使用 fetchNextPage() 函式載入。

以下範例說明如何檢查是否有下一頁,然後載入該頁面。

Swift

public struct PlaceSearchPagination {
  public var pageSize: Int
  public var hasNextPage: Bool
  public func fetchNextPage() async -> SearchByTextResponse
}

public struct SearchByTextResponse {
  public var pagination: PlaceSearchPagination?
  public var places: [Place]?
  public var error: PlaceError?
}

PlacesClient.swift
public func searchByText(with request: SearchByTextRequest) async -> SearchByTextResponse

let searchByTextRequest = SearchByTextRequest(textQuery: "restaurants",
    placeProperties: [PlaceProperty.displayName],
    locationBias: CircularCoordinateRegion(center: CLLocationCoordinate2D(latitude: 0, longitude: 0), radius: 100))

searchByTextRequest.maxResultCount = 10

var searchByTextResponse = await PlacesClient.shared.searchByText(with: searchByTextRequest)
print("Found \(searchByTextResponse.places.count) places")

searchByTextResponse.pagination.pageSize = 20

// Continue making requests until no more results are found in pagination object
while searchByTextResponse.pagination.hasNextPage {
    searchByTextResponse = await searchByTextResponse.pagination.fetchNextPage()
    print("Found \(searchByTextResponse.places.count) places")
}
    

Objective-C

GMSPlaceSearchByTextRequest *searchByTextRequest = [[GMSPlaceSearchByTextRequest alloc]
    initWithTextQuery: @"restaurants"
    placeProperties: @[GMSPlacePropertyAll]];

searchByTextRequest.maxResultCount = 10;

__block void (^recursiveCallback)(GMSPlaceSearchByTextResponse *, NSError *);
recursiveCallback = ^(GMSPlaceSearchByTextResponse * response, NSError* error) {
    NSLog(@"Found %d places", response.places.count);
    if (response.pagination.hasNextPage) {
      [response.pagination fetchNextPageWithCompletion:recursiveCallback];
   }
};
[GMSPlacesClient.sharedClient searchByTextWithRequest:searchByTextRequest  
                                           completion:recursiveCallback];
    

必要參數

使用 GMSPlaceSearchByTextRequest 物件指定搜尋所需的參數。

  • 欄位清單

    指定要傳回的地點資料屬性。傳遞 GMSPlace 屬性清單,指定要傳回的資料欄位。如果省略欄位遮罩,要求會傳回錯誤。

    欄位清單是良好的設計做法,可確保您不會要求不必要的資料,有助於避免不必要的處理時間和帳單費用。

    指定下列一或多個欄位:

    • 下列欄位會觸發 Text Search Essentials ID Only SKU:

      GMSPlacePropertyPlaceID

      如需欄位和相關 SKU 的完整清單,請參閱「地點資料欄位 (新版)」。

    • 下列欄位會觸發 Text Search Pro SKU:

      GMSPlacePropertyAddressComponents
      GMSPlacePropertyBusinessStatus
      GMSPlacePropertyCoordinate
      GMSPlacePropertyFormattedAddress
      GMSPlacePropertyIconBackgroundColor
      GMSPlacePropertyIconImageURL
      GMSPlacePropertyName
      GMSPlacePropertyPhotos
      GMSPlacePropertyPlusCode
      GMSPlacePropertyTypes
      GMSPlacePropertyUTCOffsetMinutes
      GMSPlacePropertyViewport
      GMSPlacePropertyWheelchairAccessibleEntrance

      如需欄位和相關 SKU 的完整清單,請參閱「地點資料欄位 (新版)」。

    • 下列欄位會觸發 Text Search Enterprise SKU:

      GMSPlacePropertyCurrentOpeningHours
      GMSPlacePropertySecondaryOpeningHours
      GMSPlacePropertyPhoneNumber
      GMSPlacePropertyPriceLevel
      GMSPlacePropertyRating
      GMSPlacePropertyOpeningHours
      GMSPlacePropertyUserRatingsTotal
      GMSPlacePropertyWebsite

      如需欄位和相關 SKU 的完整清單,請參閱「地點資料欄位 (新版)」。

    • 下列欄位會觸發 Text Search Enterprise Plus SKU:

      GMSPlacePropertyCurbsidePickup
      GMSPlacePropertyDelivery
      GMSPlacePropertyDineIn
      GMSPlacePropertyEditorialSummary
      GMSPlacePropertyReservable
      GMSPlacePropertyReviews
      GMSPlacePropertyServesBeer
      GMSPlacePropertyServesBreakfast
      GMSPlacePropertyServesBrunch
      GMSPlacePropertyServesDinner
      GMSPlacePropertyServesLunch
      GMSPlacePropertyServesVegetarianFood
      GMSPlacePropertyServesWine
      GMSPlacePropertyTakeout

      如需欄位和相關 SKU 的完整清單,請參閱「地點資料欄位 (新版)」。

  • textQuery

    要搜尋的文字字串,例如「餐廳」、「中正路 123 號」或「舊金山最佳景點」。

選用參數

使用 GMSPlaceSearchByTextRequest 物件指定搜尋的選用參數。

  • includedType

    讓系統在結果中只顯示符合表 A 所定義指定類型的地點。只能指定一種。例如:

    • let request = SearchByTextRequest()
      request.includedType = "bar"
    • let request = SearchByTextRequest()
      request.includedType = "pharmacy"
  • isOpenNow

    如果設為 true,則只會傳回在查詢當下營業中的地點。如果為 false,則不論營業狀態為何,一律傳回所有商家。如果將這個參數設為 false,系統會傳回未在 Google 地點資料庫中指定營業時間的地點。

  • isStrictTypeFiltering

    與 includeType 參數搭配使用。如果設為 true,系統只會傳回符合 includeType 指定類型的地點。如果設為 false (預設值),回應可能包含不符合指定類型的地點。

  • locationBias

    指定搜尋區域。這個位置會做為偏好設定,也就是說,系統會傳回指定位置周圍的結果,包括指定區域外的結果。

    您可以指定 locationRestriction 或 locationBias,但不能同時指定兩者。locationRestriction 是指定結果必須位於的區域,locationBias 則是指定結果必須靠近的區域,但可以位於該區域之外。

    請以矩形可視區域或圓形指定區域。

    • 圓形是由中心點和半徑 (以公尺為單位) 定義。半徑必須介於 0.0 至 50000.0 之間 (含首尾)。預設半徑為 0.0。 例如:

      let request = SearchByTextRequest()
      request.locationBias =  GMSPlaceCircularLocationOption(CLLocationCoordinate2DMake(40.7, -74.0), 200.0)
    • 矩形是經緯度可視區域,以兩個對角相對的低點和高點表示。低點代表矩形的西南角,高點則代表矩形的東北角。

      可視區域視為封閉區域,也就是包含邊界。緯度界限必須介於 -90 到 90 度之間 (含首尾),經度界限則必須介於 -180 到 180 度之間 (含首尾):

      • 如果 low = high,可視區域會由該單點組成。
      • 如果 low.longitude > high.longitude,經度範圍會反轉 (可視區域跨越 180 度經線)。
      • 如果 low.longitude = -180 度且 high.longitude = 180 度,可視區域會包含所有經度。
      • 如果 low.longitude = 180 度且 high.longitude = -180 度,則經度範圍為空白。
      • 如果 low.latitude > high.latitude,則緯度範圍為空。
  • locationRestriction

    指定搜尋區域。系統不會傳回指定區域以外的結果。將區域指定為矩形可視區域。如要瞭解如何定義可視區域,請參閱 locationBias 的說明。

    您可以指定 locationRestriction 或 locationBias,但不能同時指定兩者。locationRestriction 是指定結果必須位於的區域,locationBias 則是指定結果必須靠近的區域,但可以位於該區域之外。

  • maxResultCount

    指定要傳回的地點結果數量上限。必須介於 1 到 20 (預設) 之間 (含 1 和 20)。

  • minRating

    將結果限制為平均使用者評分大於或等於此限制的結果。值必須介於 0.0 至 5.0 (含) 之間,且以 0.5 為遞增單位。例如:0、0.5、1.0、...、5.0 (含)。值會無條件進位至最接近的 0.5。舉例來說,如果值為 0.6,系統會排除所有評分低於 1.0 的結果。

  • priceLevels

    將搜尋範圍限制在標示為特定價格等級的地點。 預設會選取所有價格等級。

    指定由 PriceLevel 定義的一或多個值陣列。

    例如:

        let request = SearchByTextRequest()
        request.priceLevels = [GMSPlacesPriceLevel.moderate.rawValue, GMSPlacesPriceLevel.cheap.rawValue]
  • rankPreference

    指定如何根據查詢類型,在回應中為結果排名:

    • 如果是「紐約市餐廳」這類類別查詢,預設值為 .relevance (依搜尋關聯性排序結果)。您可以將 rankPreference 設為 .relevance 或 .distance (依距離排序結果)。
    • 如果是「Mountain View, CA」這類非類別查詢,建議您不要設定 rankPreference。
  • regionCode

    用於設定回應格式的區域代碼,指定為 兩個字元的 CLDR 代碼值。這個參數也可能對搜尋結果產生偏誤效應。沒有預設值。

    如果回應中地址欄位的國家/地區名稱與區域代碼相符,地址中就會省略國家/地區代碼。

    大多數 CLDR 代碼與 ISO 3166-1 代碼相同,但有一些需要注意的例外情況。舉例來說,英國的 ccTLD 是「uk」(.co.uk),但 ISO 3166-1 代碼卻是「gb」(嚴格來說,這是「大不列顛暨北愛爾蘭聯合王國」的代碼)。這項參數可能會根據適用法律影響結果。

  • shouldIncludePureServiceAreaBusinesses

    如果為 true,則在搜尋結果中傳回完全無店面區域商家。完全無店面區域商家會直接配送或到場服務,但不在公司地址為顧客提供服務。

    例如:

    Places Swift SDK

    let request = SearchByTextRequest()
    request.shouldIncludePureServiceAreaBusinesses = true

    Swift

    let request = SearchByTextRequest()
    request.shouldIncludePureServiceAreaBusinesses: true

    Objective-C

    GMSPlaceSearchByTextRequest *request =
        [[GMSPlaceSearchByTextRequest alloc] initWithTextQuery:@"pizza in New York" placeProperties:@[GMSPlacePropertyAll]];
    request.shouldIncludePureServiceAreaBusinesses = YES;

在應用程式中顯示出處資訊

如果應用程式會顯示從 GMSPlacesClient 取得的資訊 (例如相片和評論),則也須顯示必要的出處資訊。

舉例來說,GMSPlacesClient 物件的 reviews 屬性包含最多五個 GMSPlaceReview 物件的陣列。每個 GMSPlaceReview 物件都可以包含出處和作者出處。如果應用程式會顯示評論,則也須顯示任何出處或作者資訊。

詳情請參閱出處說明文件。