본문 바로가기

프로젝트

TmapAPI로 도착지<->목적지 소요 시간 가져오기 (자동차)

 

자동차 소요시간 가져오는것도 성공 시킨 김에 좀 더 필요한 부분만 추려서 포스팅 해본다. 

 

먼저 서버단

# main.py

@app.post("/tmap/car")
def get_tmap_car(body: CarRequest = Body(...)):
    url = f"https://apis.openapi.sk.com/tmap/routes?version=1"
    headers = {
        "appKey": TMAP_API_KEY,
        "Content-Type": "application/json",
    }

    payload = {
        "startX": body.startX,
        "startY": body.startY,
        "endX": body.endX,
        "endY": body.endY,
        "startName": body.startName,
        "endName": body.endName,
        "reqCoordType": "WGS84GEO",
        "resCoordType": "WGS84GEO"
    }

    response = requests.post(url, headers=headers, json=payload)
    return response.json()

TmapAPI는 post 기반인것 같더라, get 메서드 안먹힌다.

TMAP_API_KEY는 상단에서 받아와준다. 필자는 키정보들 한꺼번에 관리하려고 .env 폴더에 전부 넣어놨다. 

load_dotenv() # .env에 apiKey를 저장했다.

app = FastAPI()

# CORS 설정 (Flutter Web용)
app.add_middleware(
    CORSMiddleware,
    allow_origins=["*"],  # 개발 단계에서만 *, 배포 시엔 도메인 지정 권장
    allow_credentials=True,
    allow_methods=["*"],
    allow_headers=["*"],
)

TMAP_API_KEY = os.getenv("TMAP_API_KEY")

 

다음은 클라이언트 단

# travel_course_detail_screan.dart

// 자동차 시간 - URL을 명확하게 구성하고 인코딩
        final carUri = Uri.parse('http://localhost:8000/tmap/car');

        debugPrint("자동차 API 요청: ${carUri.toString()}");
        final carRes = await http.post(
          carUri,
          headers: {'Content-Type': 'application/json'},
          body: jsonEncode({
            'startX': '$startLng',
            'startY': '$startLat',
            'endX': '$endLng',
            'endY': '$endLat',
            'startName': start['name'] ?? '출발지',
            'endName': end['name'] ?? '도착지',
          }),
        );
        debugPrint("자동차 API 응답 코드: ${carRes.statusCode}");

목적지 도착지는 앞 코드에서 설정해줘야 한다.

// 자동차 응답 처리
        if (carRes.statusCode == 200) {
          debugPrint("✅ 자동차차 API 응답 성공 (Tmap)");
          final carData = json.decode(carRes.body);

          if (carData['features'] != null && carData['features'].isNotEmpty) {
            final properties = carData['features'][0]['properties'];
            final totalTime = properties['totalTime']; // 단위: 초 (seconds)
            if (totalTime != null) {
              carDuration = '${(totalTime / 60).round()}분'; // 분 단위로 표시
            } else {
              debugPrint("⚠️ totalTime 없음");
            }
          } else {
            debugPrint("자동차 Tmap 응답에 features 없음");
          }
        } else {
          debugPrint("❌ 도보 API 응답 실패: ${carRes.body}");
        }