Примеры

В этом разделе описан ряд примеров запросов к API Places Insights.

Возвращать места внутри круга

Верните все рестораны в радиусе 200 метров от Трафальгарской площади в Лондоне.

  • Область поиска представляет собой круг с центром на определенной широте и долготе. Радиус этого круга составляет 200 метров, что определяет размер зоны поиска.
  • Запрошенный тип места — ресторан, и он передается с помощью includedTypes внутри typeFilters .
  • Количество запрашивается с помощью INSIGHTS_COUNT , а идентификаторы мест запрашиваются с помощью INSIGHTS_PLACES .

Отдых

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

Питон (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()
  

Исключить типы мест

Вы можете исключить типы мест из подсчета.

Следующий запрос аналогичен первому примеру, но добавляет excludedTypes к typeFilters . Вы можете использовать строку или массив строк для includedTypes и excludedTypes .

В этом примере из числа restaurant исключаются два типа мест: cafe и bakery .

Отдых

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"
            ]
        }
    }
}'
    

Питон (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()
  

Использовать основной тип

В этом примере изменяется запрос из первого примера, чтобы включать в подсчет только места, имеющие primaryType restaurant .

Отдых

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

Питон (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()
  

Пользовательский многоугольник

В этом примере показано, как использовать пользовательский многоугольник для определения области поиска. Имейте в виду, что указание INSIGHTS_PLACES ограничивает поиск областями, достаточно маленькими, чтобы вернуть до 100 идентификаторов мест. Для больших территорий используйте INSIGHTS_COUNT , чтобы обойти это ограничение и сервису не придется возвращать идентификаторы отдельных мест.

Как и раньше, в качестве типа места используется restaurant . В этом примере также представлены три других фильтра:

  • operatingStatus : В этом примере учитываются только рабочие места.
  • priceLevel : в этом примере учитываются только недорогие и умеренные места.
  • ratingFilter : в этом примере учитываются только места с оценкой от 4,0 до 5,0.

Отдых

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

Питон (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()
    
  

Географическая зона

В этом примере используется идентификатор места географической области для установки области поиска. Эти идентификаторы мест включают в себя геометрию места, например города или города. Здесь используется идентификатор места ChIJiQHsW0m3j4ARm69rRkrUF3w , что соответствует городу Маунтин-Вью, штат Калифорния .

Передача идентификатора места в API Places Insights устанавливает область поиска в пределах географической области. Идентификатор места передается с помощью place в формате places/ place_ID .

Получить идентификатор места географической зоны можно любым из следующих способов:

Отдых

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"
            ]
        }
    }
}'
    

Питон (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()