Esta seção aborda uma série de exemplos de solicitações para a API Places Insights.
Retornar lugares dentro de um círculo
Retorna todos os restaurantes em um raio de 200 m de Trafalgar Square, em Londres.
- A área de pesquisa é um círculo centralizado em uma latitude e longitude específicas. O raio desse círculo é de 200 metros, o que determina o tamanho da área de pesquisa.
- O tipo de lugar solicitado é restaurante, e ele é transmitido usando
includedTypes
emtypeFilters
. - A contagem é solicitada usando
INSIGHTS_COUNT
, e os IDs de lugar são solicitados usandoINSIGHTS_PLACES
.
Descanso
curl --location 'https://areainsights.googleapis.com/v1:computeInsights' \ --header 'X-Goog-Api-Key: API_KEY' \ --header 'Content-Type: application/json' \ --data '{ "insights": ["INSIGHT_COUNT", "INSIGHT_PLACES"], "filter": { "locationFilter": { "circle": { "latLng": { "latitude": 51.508, "longitude": -0.128}, "radius": 200 } }, "typeFilter": { "includedTypes": "restaurant" } } }'
Python (gRPC)
from google.maps import areainsights_v1 from google.maps.areainsights_v1.types import ( ComputeInsightsRequest, Filter, LocationFilter, TypeFilter, Insight ) from google.type import latlng_pb2 from google.oauth2 import service_account def get_area_insights(): # Initialize the client credentials = service_account.Credentials.from_service_account_file( 'path/to/service_account.json', scopes=['https://www.googleapis.com/auth/cloud-platform'] ) client = areainsights_v1.AreaInsightsClient( credentials=credentials ) # Create location filter with circle lat_lng = latlng_pb2.LatLng( latitude=51.508, longitude=-0.128 ) location_filter = LocationFilter( circle=LocationFilter.Circle( lat_lng=lat_lng, radius=200 ) ) # Create type filter type_filter = TypeFilter( included_types=["restaurant"] ) # Create the main filter filter = Filter( location_filter=location_filter, type_filter=type_filter ) # Create the request request = ComputeInsightsRequest( insights=[ Insight.INSIGHT_COUNT, Insight.INSIGHT_PLACES ], filter=filter ) try: # Make the request response = client.compute_insights(request=request) # Print results print(f"Total count: {response.count}") print("\nPlaces found:") for place in response.place_insights: print(f"Place ID: {place.place}") except Exception as e: print(f"Error occurred: {e}") if __name__ == "__main__": get_area_insights()
Excluir tipos de lugar
É possível excluir tipos de lugar da contagem.
A solicitação a seguir é igual ao primeiro exemplo, mas adiciona
excludedTypes
ao typeFilters
. Você pode usar uma string ou uma matriz
de strings para includedTypes
e excludedTypes
.
Este exemplo exclui dois tipos de lugar: cafe
e bakery
da contagem de restaurant
.
Descanso
curl --location 'https://areainsights.googleapis.com/v1:computeInsights' \ --header 'X-Goog-Api-Key: API_KEY' \ --header 'Content-Type: application/json' \ --data '{ "insights": ["INSIGHT_COUNT", "INSIGHT_PLACES"], "filter": { "locationFilter": { "circle": { "latLng": { "latitude": 51.508, "longitude": -0.128}, "radius": 200 } }, "typeFilter": { "includedTypes": "restaurant", "excludedTypes": [ "cafe", "bakery" ] } } }'
Python (gRPC)
from google.maps import areainsights_v1 from google.maps.areainsights_v1.types import ( ComputeInsightsRequest, Filter, LocationFilter, TypeFilter, Insight ) from google.type import latlng_pb2 from google.oauth2 import service_account def get_area_insights(): # Initialize the client with service account credentials = service_account.Credentials.from_service_account_file( 'path/to/service_account.json', scopes=['https://www.googleapis.com/auth/cloud-platform'] ) client = areainsights_v1.AreaInsightsClient( credentials=credentials ) # Create location filter with circle lat_lng = latlng_pb2.LatLng( latitude=51.508, longitude=-0.128 ) location_filter = LocationFilter( circle=LocationFilter.Circle( lat_lng=lat_lng, radius=200 ) ) # Create type filter with both included and excluded types type_filter = TypeFilter( included_types=["restaurant"], excluded_types=["cafe", "bakery"] ) # Create the main filter filter = Filter( location_filter=location_filter, type_filter=type_filter ) # Create the request request = ComputeInsightsRequest( insights=[ Insight.INSIGHT_COUNT, Insight.INSIGHT_PLACES ], filter=filter ) try: # Make the request response = client.compute_insights(request=request) # Print results print(f"Total count: {response.count}") print("\nPlaces found:") for place in response.place_insights: print(f"Place ID: {place.place}") except Exception as e: print(f"Error occurred: {e}") if __name__ == "__main__": get_area_insights()
Usar o tipo principal
Este exemplo modifica a solicitação do primeiro exemplo para incluir apenas lugares
que têm um primaryType
de restaurant
na contagem.
Descanso
curl --location 'https://areainsights.googleapis.com/v1:computeInsights' \ --header 'X-Goog-Api-Key: API_KEY' \ --header 'Content-Type: application/json' \ --data '{ "insights": ["INSIGHT_COUNT", "INSIGHT_PLACES"], "filter": { "locationFilter": { "circle": { "latLng": { "latitude": 51.508, "longitude": -0.128}, "radius": 200 } }, "typeFilter": { "includedPrimaryTypes": "restaurant" } } }'
Python (gRPC)
from google.maps import areainsights_v1 from google.maps.areainsights_v1.types import ( ComputeInsightsRequest, Filter, LocationFilter, TypeFilter, Insight ) from google.type import latlng_pb2 from google.oauth2 import service_account def get_area_insights(): # Initialize the client with service account credentials = service_account.Credentials.from_service_account_file( 'path/to/service_account.json', scopes=['https://www.googleapis.com/auth/cloud-platform'] ) client = areainsights_v1.AreaInsightsClient( credentials=credentials ) # Create location filter with circle lat_lng = latlng_pb2.LatLng( latitude=51.508, longitude=-0.128 ) location_filter = LocationFilter( circle=LocationFilter.Circle( lat_lng=lat_lng, radius=200 ) ) # Create type filter with primary types type_filter = TypeFilter( included_primary_types=["restaurant"] ) # Create the main filter filter = Filter( location_filter=location_filter, type_filter=type_filter ) # Create the request request = ComputeInsightsRequest( insights=[ Insight.INSIGHT_COUNT, Insight.INSIGHT_PLACES ], filter=filter ) try: # Make the request response = client.compute_insights(request=request) # Print results print(f"Total count: {response.count}") print("\nPlaces found:") for place in response.place_insights: print(f"Place ID: {place.place}") except Exception as e: print(f"Error occurred: {e}") if __name__ == "__main__": get_area_insights()
Polígono personalizado
Este exemplo demonstra como usar um polígono personalizado para definir sua área de pesquisa. Vale lembrar que especificar INSIGHTS_PLACES
restringe a pesquisa a áreas pequenas o suficiente para retornar até 100 IDs de lugar. Para áreas maiores, use
INSIGHTS_COUNT
para contornar essa limitação, para que o serviço não precise
retornar IDs de lugares individuais.
Como antes, o tipo de lugar usado é restaurant
. Este exemplo também apresenta
outros três filtros:
operatingStatus
: neste exemplo, são contabilizados apenas os lugares operacionais.priceLevel
: neste exemplo, são contabilizados apenas lugares com preços baratos e moderados.ratingFilter
: neste exemplo, são contabilizados apenas lugares com uma pontuação de avaliação entre 4,0 e 5,0.
Descanso
curl --location 'https://areainsights.googleapis.com/v1:computeInsights' \ --header 'X-Goog-Api-Key: API_KEY' \ --header 'Content-Type: application/json' \ --data '{ "insights": [ "INSIGHT_COUNT" ], "filter": { "locationFilter": { "customArea": { "polygon": { "coordinates": [ { "latitude": 37.776, "longitude": -122.666 }, { "latitude": 37.130, "longitude": -121.898 }, { "latitude": 37.326, "longitude": -121.598 }, { "latitude": 37.912, "longitude": -122.247 }, { "latitude": 37.776, "longitude": -122.666 } ] } } }, "typeFilter": { "includedTypes": "restaurant" }, "operatingStatus": [ "OPERATING_STATUS_OPERATIONAL" ], "priceLevels": [ "PRICE_LEVEL_INEXPENSIVE", "PRICE_LEVEL_MODERATE" ], "ratingFilter": { "minRating": 4.0, "maxRating": 5.0 } } }'
Python (gRPC)
from google.maps import areainsights_v1 from google.maps.areainsights_v1.types import ( ComputeInsightsRequest, Filter, LocationFilter, TypeFilter, Insight, RatingFilter, OperatingStatus, PriceLevel ) from google.type import latlng_pb2 from google.oauth2 import service_account def get_area_insights(): # Initialize the client with service account credentials = service_account.Credentials.from_service_account_file( 'path/to/service_account.json', scopes=['https://www.googleapis.com/auth/cloud-platform'] ) client = areainsights_v1.AreaInsightsClient( credentials=credentials ) # Create coordinates for the polygon coordinates = [ latlng_pb2.LatLng(latitude=37.776, longitude=-122.666), latlng_pb2.LatLng(latitude=37.130, longitude=-121.898), latlng_pb2.LatLng(latitude=37.326, longitude=-121.598), latlng_pb2.LatLng(latitude=37.912, longitude=-122.247), latlng_pb2.LatLng(latitude=37.776, longitude=-122.666) # Closing point ] # Create custom area with polygon using the nested structure location_filter = LocationFilter( custom_area=LocationFilter.CustomArea( polygon=LocationFilter.CustomArea.Polygon(coordinates=coordinates) ) ) # Create type filter type_filter = TypeFilter( included_types=["restaurant"] ) # Create rating filter rating_filter = RatingFilter( min_rating=4.0, max_rating=5.0 ) # Create the main filter filter = Filter( location_filter=location_filter, type_filter=type_filter, operating_status=[OperatingStatus.OPERATING_STATUS_OPERATIONAL], price_levels=[ PriceLevel.PRICE_LEVEL_INEXPENSIVE, PriceLevel.PRICE_LEVEL_MODERATE ], rating_filter=rating_filter ) # Create the request request = ComputeInsightsRequest( insights=[Insight.INSIGHT_COUNT], filter=filter ) try: # Make the request response = client.compute_insights(request=request) # Print results print(f"Total count: {response.count}") except Exception as e: print(f"Error occurred: {e}") if __name__ == "__main__": get_area_insights()
Área geográfica
Este exemplo usa um ID de lugar de área geográfica para definir a área de pesquisa.
Esses IDs incluem a geometria de um lugar, como uma cidade ou cidade. O
ID de lugar usado aqui é ChIJiQHsW0m3j4ARm69rRkrUF3w
, que corresponde à
cidade de Mountain View, Califórnia.
A transmissão do ID do lugar para a API Places Insights define a área de pesquisa como os limites da área geográfica. O ID do lugar é transmitido usando place
, no formato
places/place_ID
.
É possível receber um ID de lugar de área geográfica de uma das seguintes maneiras:
- Localizador de IDs de lugares
- API Geocoding
- Pesquisa de texto (nova)
- Pesquisa por proximidade (novo)
- API Address Validation
- Place Autocomplete
Descanso
curl --location 'https://areainsights.googleapis.com/v1:computeInsights' \ --header 'X-Goog-Api-Key: API_KEY' \ --header 'Content-Type: application/json' \ --data '{ "insights": [ "INSIGHT_COUNT" ], "filter": { "locationFilter": { "region": { "place": "places/ChIJiQHsW0m3j4ARm69rRkrUF3w" } }, "typeFilter": { "includedTypes": [ "restaurant" ] } } }'
Python (gRPC)
from google.maps import areainsights_v1 from google.maps.areainsights_v1.types import ( ComputeInsightsRequest, Filter, LocationFilter, TypeFilter, Insight ) from google.oauth2 import service_account def get_area_insights(): # Initialize the client with service account credentials = service_account.Credentials.from_service_account_file( 'path/to/service_account.json', scopes=['https://www.googleapis.com/auth/cloud-platform'] ) client = areainsights_v1.AreaInsightsClient( credentials=credentials ) # Create location filter with region location_filter = LocationFilter( region=LocationFilter.Region( place="places/ChIJiQHsW0m3j4ARm69rRkrUF3w" ) ) # Create type filter type_filter = TypeFilter( included_types=["restaurant"] ) # Create the main filter filter = Filter( location_filter=location_filter, type_filter=type_filter ) # Create the request request = ComputeInsightsRequest( insights=[Insight.INSIGHT_COUNT], filter=filter ) try: # Make the request response = client.compute_insights(request=request) # Print results print(f"Total count: {response.count}") except Exception as e: print(f"Error occurred: {e}") if __name__ == "__main__": get_area_insights()