이 문서에서는 계획된 경로를 따라 호텔, 음식점 또는 주유소를 찾는 방법을 설명합니다. Routes API를 사용하여 경로 폴리라인을 가져오고 이를 Places API Search Along Route(SAR) 요청과 함께 사용하는 방법을 알아봅니다. 또한 여행 시작 후 2시간 등 경로를 따라 검색 시작 지점을 설정하여 최상의 결과를 얻는 방법도 알아봅니다.
Routes API
경로를 따라 장소를 검색하기 위해 Routes API를 사용합니다. Routes API 응답의 경로 데이터는 출발지에서 목적지까지의 일련의 LatLong 좌표입니다. 경로 데이터에는 도로망을 따르는 구간과 단계가 포함됩니다.
경로는 인코딩된 폴리라인으로도 반환되며, 이는 SAR 요청에 입력 매개변수로 전달됩니다. 다중선 인코딩은 일련의 좌표를 단일 문자열로 저장할 수 있는 손실 압축 알고리즘입니다. Routes API에서 폴리라인을 가져오는 것은 필수가 아닙니다. 데이터를 직접 만들 수도 있지만 이 예시에서는 Routes API가 필요한 데이터를 빠르고 확실하게 가져오는 방법입니다.
이 튜토리얼에서는 런던 (-37.8167,144.9619)에서 맨체스터(-37.8155, 144.9663)까지의 경로를 사용합니다.
예시의 경로: 런던~맨체스터
1단계: Routes API에서 경로 가져오기
Routes API에서 경로를 가져오려면 다음 정보를 제공해야 합니다.
- 출발지 및 도착지 위치
- 이동 수단 (운전, 도보 등)
- 경유지 (선택사항)
- 기타 환경설정 (유료도로 제외, 고속도로 제외 등)
- 트래픽 인식 라우팅 환경설정을 사용하면 가장 정확한 추정치를 얻을 수 있지만 계산이 더 많이 필요하므로 응답 지연 시간이 늘어납니다.
{"origin":{
"location": {
"latLng":{
"latitude": -37.8167,
"longitude": 144.9619
}
}
},
"destination":{
"location": {
"latLng":{
"latitude":-37.8155,
"longitude": 144.9663
}
}
},
"routingPreference":"TRAFFIC_AWARE",
"travelMode":"DRIVE"
}
호출할 때 헤더 필드 마스크에 'encodedPolyline' 필드를 포함해야 합니다.
headers = {
"Content-Type": "application/json",
"X-Goog-FieldMask": "routes.distanceMeters,routes.duration,routes.legs,routes.polyline.encodedPolyline"
}
경로를 가져오는 방법과 경로 폴리라인을 가져오는 방법의 예가 포함된 전체 문서입니다.
요청에 이 정보를 제공하면 Routes API가 경로 객체를 반환합니다. 경로 객체에는 다음 정보가 포함됩니다.
- 경로의 총 거리
- 경로의 총 이동 시간
- 경로의 구간 및 단계
- 경로, 구간, 단계의 인코딩된 다중선입니다.
{
"routes": [
{
"legs": [
{
"distanceMeters": 321799,
"duration": "15401s",
"staticDuration": "14518s",
"polyline": {
"encodedPolyline": "y_kyH`_XOr@q@xKGnBBZ|AlGPj@Y^k@^MEqAfAQLK?eI … <rest of content removed for readability>"
},
"startLocation": {
"latLng": {
"latitude": 51.507334500000006,
"longitude": -0.1280107
}
},
"endLocation": {
"latLng": {
"latitude": 53.4808513,
"longitude": -2.2425864
}
},
"steps": [
{
"distanceMeters": 320,
"staticDuration": "82s",
"polyline": {
"encodedPolyline": "y_kyH`_XOr@q@xKGnBBZ|AlG"
},
"startLocation": {
"latLng": {
"latitude": 51.507334500000006,
"longitude": -0.1280107
}
},
"endLocation": {
"latLng": {
"latitude": 51.507207,
"longitude": -0.1323681
}
},
"navigationInstruction": {
"maneuver": "DEPART",
"instructions": "Head northwest on Trafalgar Sq/A4 toward Spring Gardens\nContinue to follow A4\nLeaving toll zone\nEntering toll zone\nLeaving toll zone in 210m at Haymarket"
},
"localizedValues": {
"distance": {
"text": "0.3 km"
},
"staticDuration": {
"text": "1 min"
}
},
# rest of the response removed for readability
2단계: Search Along the Route 요청
Places API 텍스트 검색에는 경로를 따라 장소를 검색할 수 있는 경로를 따라 검색 요청이 있습니다. 경로를 따라 검색 요청을 하려면 다음 최소 정보를 제공해야 합니다.
- 응답에 반환되는 필드의 필드 마스크
- Google Cloud 콘솔에서 사용 설정된 API의 유효한 API 키
- 찾고 있는 장소를 나타내는 검색 텍스트 문자열입니다(예: '매운 채식 식당').
- 이전 Routes API 호출에서 가져온 경로의 인코딩된 폴리라인
- Places Text Search API 엔드포인트의 URL
import requests
url = 'https://places.googleapis.com/v1/places:searchText'
api_key = 'YOUR_API_KEY' # Replace with your actual API key
route_polyline = 'YOUR_ROUTE_POLYLINE' # Replace with your encoded route polyline
headers = {
'Content-Type': 'application/json',
'X-Goog-Api-Key': api_key,
'X-Goog-FieldMask': 'places.displayName,places.formattedAddress,places.priceLevel'
}
data = {
"textQuery":
"Spicy Vegetarian Food",
"searchAlongRouteParameters": {
"polyline": {
"encodedPolyline": route_polyline
}
}
}
response = requests.post(url, headers=headers, json=data)
요청 데이터 예시
Search Along Route 요청은 경로를 따라 있는 장소 목록을 반환합니다. 다음은 예시 데이터의 일부입니다. 최대 결과 수 매개변수를 설정하여 응답 길이를 제한할 수 있으며, 필드를 추가하면 수신되는 데이터 양이 늘어납니다. Places API 응답에 관한 자세한 내용은 문서를 참고하세요.
{
"places": [
{
"formattedAddress": "33 Haymarket, London SW1Y 4HA, UK",
"displayName": {
"text": "xxx",
"languageCode": "en"
}
},
{
"formattedAddress": "224 Piccadilly, London W1J 9HP, UK",
"priceLevel": "PRICE_LEVEL_MODERATE",
"displayName": {
"text": "yyy",
"languageCode": "en"
}
},
{
"formattedAddress": "63 Neal St, London WC2H 9PJ, UK",
"displayName": {
"text": "zzz",
"languageCode": "en"
}
},
응답 데이터 예시
경로 요약 및 우회 시간
위치만 찾는 것도 좋지만 이러한 위치로 이동하는 데 걸리는 시간을 추가하면 유용합니다. Places API 텍스트 검색의 SAR은 이동 시간과 거리를 모두 포함하는 경로 요약 필드를 반환할 수도 있습니다. 경로 요약 데이터 필드는 응답 루트의 하위 요소이므로 필드 마스크에 'places.' 접두사를 포함하면 안 됩니다.
'X-Goog-FieldMask': 'places.displayName,places.formattedAddress,places.priceLevel,routingSummaries'
요약을 가져오려면 계산에 사용되는 검색의 원본 위치 매개변수도 제공해야 합니다.
"routingParameters": {
"origin": {
"latitude": -37.8167,
"longitude": 144.9619
}
}
응답을 받으면 지속 시간과 거리(미터)가 포함된 구간이 포함된 경로 요약이 있는 새로운 섹션이 있습니다.
"routingSummaries": [
{
"legs": [
{
"duration": "662s",
"distanceMeters": 3093
}
]
},
다음으로 경로에서 검색을 시작할 위치를 정의하는 방법을 살펴보겠습니다.
3단계: 경로에서 2시간 떨어진 위치 가져오기
경로 시작 지점이 아닌 경로를 따라가다가 식당을 찾고 싶어 하는 운전자의 일반적인 사용 사례를 생각해 보세요. 이 예에서 런던에서 맨체스터까지의 이동 시간은 약 4시간입니다. 운전자가 경로를 따라 2시간 거리에 있는 식당을 찾고 싶어 합니다. 이 요청은 120분 * 60초 = 7200초의 기간을 가져옵니다.
Routes API 응답에는 경로의 각 구간과 구간의 각 단계의 시간이 포함됩니다. 요청의 필드 마스크에 'legs' 필드를 포함해야 합니다. 누적된 시간이 2시간 또는 7,200초 한도에 도달할 때까지 구간과 단계를 반복합니다. 그러면 SAR 요청의 원점으로 설정할 다리와 단계를 찾은 것입니다.
작업 속도를 높이려면 Python용 폴리라인 라이브러리를 사용해 보세요. 이 함수를 사용하여 'polyline.endodedPolyline' 데이터 필드에서 좌표를 가져올 수 있습니다.
환경 터미널에서 다음 명령어를 실행합니다.
> pip install polyline
import requests
import polyline
# We've covered getting a Routes API response earlier,
data = response.json()
# Extract the first route and its encoded polyline
route = data["routes"][0]
polyline_points = polyline.decode(route["polyline"]["encodedPolyline"])
# Calculate total duration of the route in seconds
total_duration_seconds = route["duration"]
# Calculate the desired time offset in seconds, 2h = 120 minutes * 60
desired_time_offset_seconds = time_offset_minutes * 60
# Iterate through the legs and steps to find the point at the desired time offset
elapsed_time_seconds = 0
for leg in route["legs"]:
for step in leg["steps"]:
step_duration_seconds = step["staticDuration"]
# Check if the desired time offset falls within this step, remove last "s" from string and convert to int
second_value = int(step_duration_seconds[:-1])
if elapsed_time_seconds + second_value >= desired_time_offset_seconds:
# Interpolate to find the exact point within the step
fraction_of_step = (desired_time_offset_seconds - elapsed_time_seconds) / second_value
step_polyline_points = polyline.decode(step["polyline"]["encodedPolyline"])
index = int(len(step_polyline_points) * fraction_of_step)
return step_polyline_points[index]
elapsed_time_seconds += second_value
# If the point is not found (e.g., time offset exceeds route duration)
return None
이제 여행 시작 후 2시간이 지난 시점의 경로 위치를 찾았으므로 요청에 사용할 수 있습니다. 'routingParameters' 매개변수의 일부인 'origin' 매개변수에 위도와 경도를 추가하기만 하면 됩니다. 앞서 다룬 'routingSummaries' 데이터 필드를 사용하는 것이 좋습니다. 원하는 경우 이동 모드, 통행료를 피하기 위한 안내와 같은 추가 매개변수를 추가할 수도 있습니다.
"routingParameters": {
"origin": {
"latitude": xx.xxxx,
"longitude": yy.yyyy
},
"travelMode":"DRIVE",
"routeModifiers": {
"avoidTolls": true
}
}
결과 예 (검색 출처를 표시하기 위해 자동차 아이콘이 추가됨).
이미지에서 볼 수 있듯이 API는 경로의 끝으로 치우친 장소를 반환하며, 여행 중간쯤부터 결과가 시작됩니다. 검색은 장소 관련성, 거리 등의 요인을 고려하는 동일한 Google 지도 플랫폼 데이터를 기반으로 합니다.
결론
이 튜토리얼에서는 두 개의 Google Maps Platform API인 Routes와 Places를 결합하여 여행을 계획하고 여행 시작 2시간 후에 식사할 장소를 찾는 방법을 알아봤습니다. 필요한 단계는 각 단계의 위도 및 경도 좌표가 포함된 인코딩된 폴리라인을 가져오고 최상의 결과를 얻기 위해 경로를 따라 검색 요청 원본을 설정하는 것입니다.
이 기능은 Places API에서 사용할 수 있는 기존 텍스트 검색 및 주변 검색에 강력한 새 도구를 추가합니다. 최적의 검색 시작점을 찾기 위해 운전자 위치를 시작점으로 사용할 수 있도록 위치 서비스를 추가하는 것이 논리적인 후속 조치입니다. 또한 이 기능은 선호하는 식사 옵션을 음성으로 말하는 차량 내 음성 어시스턴트와 완벽하게 함께 작동합니다.
다음 작업
- 문서의 예시를 사용해 보세요.
- 의견 남기기
추천 추가 자료:
참여자
Google에서 이 문서를 유지관리합니다. 다음 기여자가 원래 작성했습니다.
주요 저자: 미코 토이바넨 | Google Maps Platform 솔루션 엔지니어