
안녕하세요!
오늘은 파이썬으로 구글 map api를 사용해서 장소 이미지와 지도를 넣는 법에 대해서 알아보려고 합니다.
결과물은 아래와 같이 나옵니다! 🙂
블로그를 쓸 때, 장소를 넣는 경우가 생길 수 있습니다. 파이썬으로 글을 작성하거나 html 구조로 글을 작성하시는 분들에게는 이러한 api가 굉장히 유용할 수 있겠죠. (제가 그렇습니다)

돈이 드나요?
이 부분이 굉장히 애매하지만, 정답을 내리자면 나름 이렇습니다.
“돈이 들지만, 안듭니다?”
이유는 이렇습니다.
Google Maps API는 기본적으로 유료 서비스입니다. 하지만 일부 기능은 무료 할당량(Free Tier) 내에서 사용할 수 있습니다.
요금 체계 개요
- Google은 월 $200의 무료 크레딧을 제공합니다.
- 무료 크레딧을 초과하면 API 사용량에 따라 요금이 부과됩니다.
- 각 API의 요금은 사용 유형(지도 로드, 경로 탐색, 장소 검색 등)에 따라 다릅니다.
주요 API 및 요금
API 유형 | 무료 할당량(월) | 초과 시 요금 |
---|---|---|
Maps JavaScript API (웹사이트 지도 표시) | 28,000회 로드 | 1,000회당 $7.00 |
Static Maps API (정적 지도 이미지) | 100,000회 로드 | 1,000회당 $2.00 |
Directions API (길찾기) | 40,000회 요청 | 1,000회당 $5.00 |
Geocoding API (주소 ↔ 좌표 변환) | 40,000회 요청 | 1,000회당 $5.00 |
Places API (장소 검색) | 11,000회 요청 | 1,000회당 $17.00 |
무료로 사용 가능한 방법
- 월 $200 무료 크레딧 활용
- 일반적인 개인 프로젝트나 소규모 서비스라면 이 크레딧으로 대부분 무료 사용 가능.
- OpenStreetMap(무료 대체 API) 활용
- Google Maps API가 부담된다면, Leaflet + OpenStreetMap 같은 오픈소스 대안을 고려 가능.
- 요금 한도 설정
- Google Cloud Console에서 결제 한도를 설정하면 예산 초과 방지 가능.
결론
Google Maps API는 유료지만, 월 $200 크레딧을 제공하므로 소규모 프로젝트에서는 추가 비용 없이 사용할 수 있습니다.
어떻게 사용할까
구글 maps api를 먼저 사용할 수 있도록 구글 클라우드 콘솔에서 나의 프로젝트에 구글 maps api를 추가해주어야 합니다.

여기서 나의 구글 맵 api키까지 받을 수 있고, 이것을 가지고 있어야 합니다.
파이썬 코드 짜는 법
이제 파이썬 코드를 짜야겠죠?
아마 하면서 막히는 부분이 많고 제가 설명드린 부분이 적게 느껴질 수 있습니다. 하지만, 조금씩 알아보는 것이 더 도움이 될 수 있습니다.
코드 구조로는 지역명으로 위도와 경도를 받고 그 정보를 바탕으로 구글 맵에 검색하여 이미지나 위치를 임베드할 수 있는 url을 받습니다.
def get_coordinates(city):
"""도시 이름을 받아 위도와 경도를 반환하는 간단한 함수"""
url = f"https://maps.googleapis.com/maps/api/geocode/json?address={quote(city)}&key={GOOGLE_API_KEY}"
try:
response = requests.get(url, timeout=10).json()
if response["status"] == "OK":
location = response["results"][0]["geometry"]["location"]
return f"{location['lat']},{location['lng']}"
else:
print(f"좌표를 가져올 수 없음 ({city}): {response['status']}")
return "37.5665,126.9780" # 기본값 (서울 좌표)
except requests.exceptions.RequestException as e:
print(f"Geocoding API 오류 ({city}): {e}")
return "37.5665,126.9780" # 기본값
그리고 나서 아래와 같이 해당 위치에 있는 장소에 대한 정보를 몇가지 가져올 수 있습니다.
제 코드의 경우 type=tourist_attraction 로 설정하여 여행객들이 찾을만 한 어트랙션 장소를 위주로 검색하도록 했습니다.
def get_google_attractions(city):
location = get_coordinates(city)
url = f"https://maps.googleapis.com/maps/api/place/nearbysearch/json?location={location}&radius=5000&type=tourist_attraction&key={GOOGLE_API_KEY}"
try:
response = requests.get(url, timeout=10).json()
attractions = []
for result in response.get("results", []):
name = result.get("name")
address = result.get("vicinity", "주소 없음")
postal_code = result.get("plus_code", {}).get("compound_code", "우편번호 없음").split(" ")[0] if result.get("plus_code") else "우편번호 없음"
place_id = result.get("place_id")
# Place Details 요청으로 사진 최대 4장 가져오기
details_url = f"https://maps.googleapis.com/maps/api/place/details/json?place_id={place_id}&fields=photos&key={GOOGLE_API_KEY}"
details_response = requests.get(details_url, timeout=10).json()
photos = details_response.get("result", {}).get("photos", [])
photo_urls = []
for photo in photos[:4]:
photo_reference = photo.get("photo_reference")
if photo_reference:
photo_url = f"https://maps.googleapis.com/maps/api/place/photo?maxwidth=400&photoreference={photo_reference}&key={GOOGLE_API_KEY}"
photo_urls.append(photo_url)
while len(photo_urls) < 4:
photo_urls.append("")
# Google Maps Embed URL 생성
map_embed_url = f"https://www.google.com/maps/embed/v1/place?key={GOOGLE_API_KEY}&q={quote(name + ' ' + city)}"
attractions.append({
"name": name,
"description": f"{name}은(는) {city}에서 독특한 매력을 자랑하는 명소입니다.",
"images": photo_urls[:4], #반환 받을 이미지 개수 선택하기
"address": address,
"postal_code": postal_code,
"map_embed_url": map_embed_url
})
if len(attractions) > 3:
attractions = random.sample(attractions, 3)
else:
attractions = attractions[:3]
print(f"선택된 관광지 수: {len(attractions)}")
return attractions
except requests.exceptions.RequestException as e:
print(f"Google Maps API 오류 ({city}): {e}")
return []
이미지 개수도 선택을 할 수 있고, 몇개의 장소를 선택할지도 모두 선택할 수 있습니다.
코드를 한줄한줄 잘 보고 정해보면 좋겠죠?
전체 코드
import requests
import random
from urllib.parse import quote
import os
# 환경 변수에서 Google API 키 가져오기 (또는 직접 입력)
GOOGLE_API_KEY = "api키 넣기" # 여기에 실제 API 키를 넣으세요
def get_coordinates(city):
"""도시 이름을 받아 위도와 경도를 반환하는 간단한 함수"""
url = f"https://maps.googleapis.com/maps/api/geocode/json?address={quote(city)}&key={GOOGLE_API_KEY}"
try:
response = requests.get(url, timeout=10).json()
if response["status"] == "OK":
location = response["results"][0]["geometry"]["location"]
return f"{location['lat']},{location['lng']}"
else:
print(f"좌표를 가져올 수 없음 ({city}): {response['status']}")
return "37.5665,126.9780" # 기본값 (서울 좌표)
except requests.exceptions.RequestException as e:
print(f"Geocoding API 오류 ({city}): {e}")
return "37.5665,126.9780" # 기본값
def get_google_attractions(city):
location = get_coordinates(city)
url = f"https://maps.googleapis.com/maps/api/place/nearbysearch/json?location={location}&radius=5000&type=tourist_attraction&key={GOOGLE_API_KEY}"
try:
response = requests.get(url, timeout=10).json()
attractions = []
for result in response.get("results", []):
name = result.get("name")
address = result.get("vicinity", "주소 없음")
postal_code = result.get("plus_code", {}).get("compound_code", "우편번호 없음").split(" ")[0] if result.get("plus_code") else "우편번호 없음"
place_id = result.get("place_id")
# Place Details 요청으로 사진 최대 4장 가져오기
details_url = f"https://maps.googleapis.com/maps/api/place/details/json?place_id={place_id}&fields=photos&key={GOOGLE_API_KEY}"
details_response = requests.get(details_url, timeout=10).json()
photos = details_response.get("result", {}).get("photos", [])
photo_urls = []
for photo in photos[:4]:
photo_reference = photo.get("photo_reference")
if photo_reference:
photo_url = f"https://maps.googleapis.com/maps/api/place/photo?maxwidth=400&photoreference={photo_reference}&key={GOOGLE_API_KEY}"
photo_urls.append(photo_url)
while len(photo_urls) < 4:
photo_urls.append("")
# Google Maps Embed URL 생성
map_embed_url = f"https://www.google.com/maps/embed/v1/place?key={GOOGLE_API_KEY}&q={quote(name + ' ' + city)}"
attractions.append({
"name": name,
"description": f"{name}은(는) {city}에서 독특한 매력을 자랑하는 명소입니다.",
"images": photo_urls[:4], #반환 받을 이미지 개수 선택하기
"address": address,
"postal_code": postal_code,
"map_embed_url": map_embed_url
})
if len(attractions) > 3:
attractions = random.sample(attractions, 3)
else:
attractions = attractions[:3]
print(f"선택된 관광지 수: {len(attractions)}")
return attractions
except requests.exceptions.RequestException as e:
print(f"Google Maps API 오류 ({city}): {e}")
return []
# 테스트 코드
def test_get_google_attractions():
# 테스트할 도시
test_city = "Seoul" # 원하는 도시로 변경 가능
print(f"\n{test_city}의 관광지 검색 시작...")
attractions = get_google_attractions(test_city)
# 결과 출력
if attractions:
for i, attraction in enumerate(attractions, 1):
print(f"\n관광지 {i}:")
print(f"이름: {attraction['name']}")
print(f"설명: {attraction['description']}")
print(f"주소: {attraction['address']}")
print(f"우편번호: {attraction['postal_code']}")
print("사진 URL:")
for j, url in enumerate(attraction['images'], 1):
print(f" {j}. {url if url else '사진 없음'}")
print(f"지도 Embed URL: {attraction['map_embed_url']}")
else:
print("관광지를 찾을 수 없습니다.")
if __name__ == "__main__":
test_get_google_attractions()
전체 코드는 이렇습니다.
그리고 반환되는 값은 이렇습니다. 지금은 한개만 가져왔는데, 관광지 3곳과 각각의 이미지 url 3개씩과 각자의 임베드 url을 받을 수 있습니다.
관광지 #:
이름: Myeongdong Cathedral
설명: Myeongdong Cathedral은(는) Seoul에서 독특한 매력을 자랑하는 명소입니다.
주소: 74 Myeongdong-gil, Jung District
우편번호: HX7P+8V
사진 URL:

실제 적용된 블로그 글이 아래와 같으니 한번 참고해보세요!

오늘도 슬기로운 코딩 생활 되세요!