Ricerca nelle vicinanze (novità)

Seleziona la piattaforma:Android iOS JavaScript Servizio web
Sviluppatori dello Spazio economico europeo (SEE)

Una richiesta di ricerca nelle vicinanze (nuova) prende come input la regione da cercare specificata come cerchio, definita dalle coordinate di latitudine e longitudine del punto centrale del cerchio e dal raggio in metri. La richiesta restituisce un elenco di luoghi corrispondenti, ognuno rappresentato da un oggetto GMSPlace, all'interno dell'area di ricerca specificata.

Per impostazione predefinita, la risposta contiene luoghi di tutti i tipi all'interno dell'area di ricerca. Puoi filtrare facoltativamente la risposta specificando un elenco di tipi di luoghi da includere o escludere esplicitamente dalla risposta. Ad esempio, puoi specificare di includere nella risposta solo i luoghi di tipo "ristorante", "panificio" e "bar" oppure escludere tutti i luoghi di tipo "scuola".

Richieste di Nearby Search (nuovo)

Invia una richiesta di ricerca nelle vicinanze chiamando GMSPlacesClient searchNearbyWithRequest:, passando un oggetto GMSPlaceSearchNearbyRequest che definisce i parametri della richiesta e un metodo di callback, di tipo GMSPlaceSearchNearbyResultCallback, per gestire la risposta.

L'oggetto GMSPlaceSearchNearbyRequest specifica tutti i parametri obbligatori e facoltativi per la richiesta. I parametri obbligatori includono:

  • L'elenco dei campi da restituire nell'oggetto GMSPlace, chiamato anche maschera di campo, come definito da GMSPlaceProperty. Se non specifichi almeno un campo nell'elenco dei campi o se ometti l'elenco dei campi, la chiamata restituisce un errore.
  • La limitazione della posizione, ovvero il cerchio che definisce l'area di ricerca.

Questa richiesta di ricerca nelle vicinanze specifica che gli oggetti GMSPlace della risposta contengono il nome del luogo (GMSPlacePropertyName) e le coordinate del luogo (GMSPlacePropertyCoordinate) per ogni oggetto GMSPlace nei risultati di ricerca. Inoltre, filtra la risposta in modo da restituire solo i luoghi di tipo "ristorante" e "caffetteria".

Places Swift SDK

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
}

Swift

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

// Define the search area as a 500 meter diameter circle in San Francisco, CA.
let circularLocationRestriction = GMSPlaceCircularLocationOption(CLLocationCoordinate2DMake(37.7937, -122.3965), 500)

// Specify the fields to return in the GMSPlace object for each place in the response.
let placeProperties = [GMSPlaceProperty.name, GMSPlaceProperty.coordinate].map {$0.rawValue}

// Create the GMSPlaceSearchNearbyRequest, specifying the search area and GMSPlace fields to return.
var request = GMSPlaceSearchNearbyRequest(locationRestriction: circularLocationRestriction, placeProperties: placeProperties)
let includedTypes = ["restaurant", "cafe"]
request.includedTypes = includedTypes

let callback: GMSPlaceSearchNearbyResultCallback = { [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().searchNearby(with: request, callback: callback)

Objective-C

// Array to hold the places in the response
_placeResults = [NSArray array];

// Define the search area as a 500 meter diameter circle in San Francisco, CA.
id<GMSPlaceLocationRestriction> circularLocation = GMSPlaceCircularLocationOption(CLLocationCoordinate2DMake(37.7937, -122.3965), 500);

// Create the GMSPlaceSearchNearbyRequest, specifying the search area and GMSPlace fields to return.
GMSPlaceSearchNearbyRequest *request = [[GMSPlaceSearchNearbyRequest alloc]
  initWithLocationRestriction:circularLocation
              placeProperties:@[ GMSPlacePropertyName, GMSPlacePropertyCoordinate ]];

// Set the place types to filter on.
NSArray<NSString *> *includedTypes = @[ @"restaurant", @"cafe" ];
request.includedTypes = [[NSMutableArray alloc] initWithArray:includedTypes];

[_placesClient searchNearbyWithRequest:request
  callback:^(NSArray<GMSPlace *> *_Nullable places, NSError *_Nullable error) {
    if (error != nil) {
      NSLog(@"An error occurred %@", [error localizedDescription]);
      return;
    } else {
        // Get list of places.
        _placeResults = places;
    }
  }
];

Risposte alla ricerca nelle vicinanze

L'API Nearby Search restituisce un array di corrispondenze sotto forma di oggetti GMSPlace, con un oggetto GMSPlace per ogni luogo corrispondente.

Ottenere lo stato aperto

L'oggetto GMSPlacesClient contiene una funzione membro chiamata isOpenWithRequest (isOpenRequest in Swift e isPlaceOpenRequest in GooglePlacesSwift) che restituisce una risposta che indica se il luogo è attualmente aperto, in base all'ora specificata nella chiamata.

Questo metodo accetta un singolo argomento di tipo GMSPlaceIsOpenWithRequest che contiene:

  • Un oggetto GMSPlace o una stringa che specifica un ID luogo. Per ulteriori informazioni sulla creazione dell'oggetto Place con i campi necessari, consulta Dettagli del luogo.
  • Un oggetto NSDate (Obj-C) o Date (Swift) facoltativo che specifica l'ora che vuoi controllare. Se non viene specificato alcun orario, il valore predefinito è ora.
  • Un metodo GMSPlaceOpenStatusResponseCallback per gestire la risposta.
  • >

Il metodo GMSPlaceIsOpenWithRequest richiede l'impostazione dei seguenti campi nell'oggetto GMSPlace:

  • GMSPlacePropertyUTCOffsetMinutes
  • GMSPlacePropertyBusinessStatus
  • GMSPlacePropertyOpeningHours
  • GMSPlacePropertyCurrentOpeningHours
  • GMSPlacePropertySecondaryOpeningHours

Se questi campi non vengono forniti nell'oggetto Place o se passi un ID luogo, il metodo utilizza GMSPlacesClient GMSFetchPlaceRequest: per recuperarli.

isOpenWithRequest risposta

isOpenWithRequest restituisce un oggetto GMSPlaceIsOpenResponse contenente un valore booleano denominato status che indica se l'attività è aperta, chiusa o se lo stato è sconosciuto.

Lingua Valore se aperto Valore se chiuso Valore se lo stato è sconosciuto
Places Swift true false nil
Swift .open .closed .unknown
Objective-C GMSPlaceOpenStatusOpen GMSPlaceOpenStatusClosed GMSPlaceOpenStatusUnknown

Fatturazione per isOpenWithRequest

  • I campi GMSPlacePropertyUTCOffsetMinutes e GMSPlacePropertyBusinessStatus vengono addebitati in base allo SKU dati di base. Il resto dell'orario di apertura viene addebitato in base allo SKU Place Details Enterprise.
  • Se il tuo GMSPlace oggetto ha già questi campi da una richiesta precedente, non ti verrà addebitato alcun costo.

Esempio: inviare una richiesta GMSPlaceIsOpenWithRequest

L'esempio seguente mostra come inizializzare un GMSPlaceIsOpenWithRequest all'interno di un oggetto GMSPlace esistente.

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

Parametri obbligatori

Utilizza l'oggetto GMSPlaceSearchNearbyRequest per specificare i parametri richiesti per la ricerca.

  • Elenco dei campi

    Quando richiedi i dettagli del luogo, devi specificare i dati da restituire nell'oggetto GMSPlace per il luogo come maschera di campo. Per definire la maschera del campo, passa un array di valori da GMSPlaceProperty all'oggetto GMSPlaceSearchNearbyRequest. Il mascheramento dei campi è una buona pratica di progettazione per assicurarsi di non richiedere dati non necessari, il che aiuta a evitare tempi di elaborazione e addebiti non necessari.

    Specifica uno o più dei seguenti campi:

    • I seguenti campi attivano lo SKU Nearby Search Pro:

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

    • I seguenti campi attivano lo SKU Nearby Search Enterprise:

      GMSPlacePropertyCurrentOpeningHours
      GMSPlacePropertySecondaryOpeningHours
      GMSPlacePropertyPhoneNumber
      GMSPlacePropertyPriceLevel
      GMSPlacePropertyRating
      GMSPlacePropertyOpeningHours
      GMSPlacePropertyUserRatingsTotal
      GMSPlacePropertyWebsite

    • I seguenti campi attivano lo SKU di Nearby Search Enterprise Plus:

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

    L'esempio seguente passa un elenco di due valori di campo per specificare che l'oggetto GMSPlace restituito da una richiesta contiene i campi name e placeID:

    Places Swift SDK

    // Specify the place data types to return.
    let fields: [PlaceProperty] = [.placeID, .displayName]
            

    Swift

    // Specify the place data types to return.
    let fields: [GMSPlaceProperty] = [.placeID, .name]
            

    Objective-C

    // Specify the place data types to return.
    NSArray<GMSPlaceProperty *> *fields = @[GMSPlacePropertyPlaceID, GMSPlacePropertyName];
            
  • locationRestriction

    Un oggetto GMSPlaceLocationRestriction che definisce la regione da cercare specificata come cerchio, definita dal punto centrale e dal raggio in metri. Il raggio deve essere compreso tra 0,0 e 50.000,0 inclusi. Il raggio predefinito è 0.0. Devi impostarlo nella richiesta su un valore maggiore di 0,0.

Parametri facoltativi

Utilizza l'oggetto GMSPlaceSearchNearbyRequest per specificare i parametri facoltativi per la ricerca.

  • includedTypes/excludedTypes, includedPrimaryTypes/excludedPrimaryTypes

    Consente di specificare un elenco di tipi dalla tabella A Tabella A utilizzata per filtrare i risultati di ricerca. È possibile specificare fino a 50 tipi in ogni categoria di limitazione dei tipi.

    Un luogo può avere un solo tipo principale tra i tipi Tabella A associati. Ad esempio, il tipo principale potrebbe essere "mexican_restaurant" o "steak_house". Utilizza includedPrimaryTypes e excludedPrimaryTypes per filtrare i risultati in base al tipo principale di un luogo.

    Un luogo può avere anche più valori di tipo dai tipi Tabella A associati. Ad esempio, un ristorante potrebbe avere i seguenti tipi: "seafood_restaurant", "restaurant", "food", "point_of_interest", "establishment". Utilizza includedTypes e excludedTypes per filtrare i risultati nell'elenco dei tipi associati a un luogo.

    Quando specifichi un tipo principale generale, ad esempio "restaurant" o "hotel", la risposta può contenere luoghi con un tipo principale più specifico di quello specificato. Ad esempio, specifichi di includere un tipo principale di "restaurant". La risposta può quindi contenere luoghi con un tipo principale di "restaurant", ma può anche contenere luoghi con un tipo principale più specifico, come "chinese_restaurant" o "seafood_restaurant".

    Se una ricerca viene specificata con più limitazioni di tipo, vengono restituiti solo i luoghi che soddisfano tutte le limitazioni. Ad esempio, se specifichi {"includedTypes": ["restaurant"], "excludedPrimaryTypes": ["steak_house"]}, i luoghi restituiti forniscono servizi correlati "restaurant", ma non operano principalmente come "steak_house".

    includedTypes

    Un elenco dei tipi di luoghi da Tabella A da cercare. Se questo parametro viene omesso, vengono restituiti luoghi di tutti i tipi.

    excludedTypes

    Un elenco di tipi di luoghi da Tabella A da escludere da una ricerca.

    Se nella richiesta specifichi sia includedTypes (ad esempio "school") sia excludedTypes (ad esempio "primary_school"), la risposta include i luoghi classificati come "school", ma non come "primary_school". La risposta include i luoghi che corrispondono ad almeno uno dei includedTypes e a nessuno dei excludedTypes.

    Se sono presenti tipi in conflitto, ad esempio un tipo che compare sia in includedTypes che in excludedTypes, viene restituito un errore INVALID_REQUEST.

    includedPrimaryTypes

    Un elenco di tipi di luoghi principali della tabella A da includere in una ricerca.

    excludedPrimaryTypes

    Un elenco di tipi di luoghi principali da Tabella A da escludere da una ricerca.

    Se sono presenti tipi primari in conflitto, ad esempio un tipo che compare sia in includedPrimaryTypes che in excludedPrimaryTypes, viene restituito un errore INVALID_ARGUMENT.

  • maxResultCount

    Specifica il numero massimo di risultati di luoghi da restituire. Deve essere compreso tra 1 e 20 (valore predefinito) inclusi.

  • rankPreference

    Il tipo di ranking da utilizzare. Se questo parametro viene omesso, i risultati vengono classificati in base alla popolarità. Può essere uno dei seguenti:

    • .popularity (impostazione predefinita) Ordina i risultati in base alla loro popolarità.
    • .distance Ordina i risultati in ordine crescente in base alla distanza dalla posizione specificata.
  • regionCode

    Il codice regione utilizzato per formattare la risposta, specificato come valore di un codice CLDR a due caratteri. Non esiste un valore predefinito.

    Se il nome del paese del campo formattedAddress nella risposta corrisponde a regionCode, il codice paese viene omesso da formattedAddress. Questo parametro non ha effetto su adrFormatAddress, che include sempre il nome del paese, né su shortFormattedAddress, che non lo include mai.

    La maggior parte dei codici CLDR sono identici ai codici ISO 3166-1, con alcune eccezioni degne di nota. Ad esempio, il TLD specifico per paese del Regno Unito è "uk" (.co.uk), mentre il suo codice ISO 3166-1 è"gb " (tecnicamente per l'entità "Regno Unito di Gran Bretagna e Irlanda del Nord"). Il parametro può influire sui risultati in base alla legge vigente.

Visualizzare le attribuzioni nell'app

Quando la tua app mostra informazioni ottenute da GMSPlacesClient, come foto e recensioni, deve mostrare anche le attribuzioni richieste.

Ad esempio, la proprietà reviews dell'oggetto GMSPlacesClient contiene un array di massimo cinque oggetti GMSPlaceReview. Ogni oggetto GMSPlaceReview può contenere attribuzioni e attribuzioni dell'autore. Se mostri la recensione nella tua app, devi mostrare anche l'attribuzione o l'attribuzione dell'autore.

Per saperne di più, consulta la documentazione sulle attribuzioni.