Ví dụ

Phần này trình bày một loạt yêu cầu mẫu cho API Thông tin chi tiết về địa điểm.

Trả về các địa điểm trong một vòng tròn

Trả về tất cả nhà hàng trong bán kính 200 m từ quảng trường Trafalgar, London.

  • Khu vực tìm kiếm là một vòng tròn có tâm là vĩ độ và kinh độ cụ thể. Bán kính của vòng tròn này là 200 mét, xác định kích thước của khu vực tìm kiếm.
  • Loại địa điểm được yêu cầu là nhà hàng và loại này được truyền bằng cách sử dụng includedTypes trong typeFilters.
  • Số lượng được yêu cầu bằng INSIGHTS_COUNTmã địa điểm được yêu cầu bằng INSIGHTS_PLACES.

Nghỉ ngơi

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()
  

Loại trừ loại địa điểm

Bạn có thể loại trừ các loại địa điểm khỏi số liệu tính.

Yêu cầu sau đây giống với ví dụ đầu tiên, nhưng thêm excludedTypes vào typeFilters. Bạn có thể sử dụng một chuỗi hoặc một mảng chuỗi cho includedTypesexcludedTypes.

Ví dụ này loại trừ hai loại địa điểm: cafebakery khỏi số lượng restaurant.

Nghỉ ngơi

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()
  

Sử dụng loại chính

Ví dụ này sửa đổi yêu cầu từ ví dụ đầu tiên để chỉ bao gồm những địa điểm có primaryTyperestaurant trong số lượng.

Nghỉ ngơi

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()
  

Đa giác tuỳ chỉnh

Ví dụ này minh hoạ cách sử dụng đa giác tuỳ chỉnh để xác định khu vực tìm kiếm. Xin lưu ý rằng việc chỉ định INSIGHTS_PLACES sẽ giới hạn phạm vi tìm kiếm ở những khu vực đủ nhỏ để trả về tối đa 100 mã địa điểm. Đối với các khu vực lớn hơn, hãy sử dụng INSIGHTS_COUNT để bỏ qua giới hạn này để dịch vụ không cần trả về mã địa điểm riêng lẻ.

Giống như trước đây, loại địa điểm được sử dụng là restaurant. Ví dụ này cũng giới thiệu thêm ba bộ lọc khác:

  • operatingStatus: Ví dụ này chỉ tính các địa điểm hoạt động.
  • priceLevel: Ví dụ này chỉ tính những địa điểm có giá không đắt và giá vừa phải.
  • ratingFilter: Ví dụ này chỉ tính những địa điểm có điểm đánh giá từ 4 đến 5.

Nghỉ ngơi

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()
    
  

Khu vực địa lý

Ví dụ này sử dụng mã địa điểm Khu vực địa lý để đặt khu vực tìm kiếm. Các mã địa điểm này bao gồm hình học của một địa điểm, chẳng hạn như một thị trấn hoặc thành phố. Mã địa điểm dùng ở đây là ChIJiQHsW0m3j4ARm69rRkrUF3w, tương ứng với thành phố Mountain View, California.

Việc truyền mã địa điểm đến API Thông tin chi tiết về địa điểm sẽ đặt phạm vi tìm kiếm thành ranh giới của khu vực địa lý. Mã địa điểm được truyền bằng place, ở định dạng places/place_ID.

Bạn có thể lấy mã địa điểm Khu vực địa lý theo một trong những cách sau:

Nghỉ ngơi

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()