사이드 프로젝트를 진행하며 DB 구축을 진행하고 있다. 지도맵에서 보여줄 필요가 있어서 크롤링을 통해 주소를 확보하면 해당 주소를 위도, 경도로 변환하는 작업이다.
주소를 입력 -> Lat, Lng로 변환하는 작업인데 찾아보니 크게 2가지 방법으로 가능하다. 첫번째는 오픈소스 API를 사용하는 방법이고 두번째는 Kakao Map을 통해서 위도 경도를 획득할 수 있다.
Nominatim
Geo 관련해서 여러 API를 제공하는 오픈소스인 듯 하다. 사이트를 들어가보니 다음과 같이 서비스를 소개하고 있다.
Open-source geocoding
with OpenStreetMap data
여러 블로그에서도 소개하고 있어서 다음과 같이 소스를 작성하고 실행해 보았다.
from geopy.geocoders import Nominatim
def get_lat_lng(address):
geolocoder = Nominatim(user_agent = 'South Korea', timeout=None)
geo = geolocoder.geocode(address)
crd = {"lat": str(geo.latitude), "lng": str(geo.longitude)}
print(crd)
return crd
get_lat_lng("경기 성남시 분당구 판교역로 136")
{'lat': '37.3960504', 'lng': '127.109674'}
경기 성남시 분당구 판교역로 136 (판교역)을 입력하니 정상적으로 위도와 경도를 획득할 수 있다. 다만 Nominatim이 오픈소스다 보니 트래픽 초과로 인해 서비스가 원활히 돌아가지 않을때도 있었다. 한국시간으로 낮에 테스트 했을때는 에러가 종종 발생하곤 했다.
두번째 방법으로는 국내에서 제공하는 카카오 API를 활용해 위도, 경도를 확인해 보겠다.
Kakao Map API
// API 결과값이 없을 수 있으니 꼭 try-except문으로 작성해주자
def get_kakao_lat_lng(address):
try:
url = 'https://dapi.kakao.com/v2/local/search/address.json?query=' + address
headers = {"Authorization": "KakaoAK YOUR_API_KEY"}
api_json = json.loads(str(requests.get(url,headers=headers).text))
address = api_json['documents'][0]['address']
crd = {"lat": str(address['y']), "lng": str(address['x'])}
return crd
except:
crd = {"lat":0,"lng":0}
return crd;
get_kakao_lat_lng("경기 성남시 분당구 판교역로 136")
{'lat': '37.3925072208217', 'lng': '127.110430292919'}
Kakao Map API를 통해 위도와 경도를 확인할 수 있다. Open API다 보니 1일 요청횟수가 제한되어 있지만 이정도면 충분히 요청하고도 남을듯 !?
파이썬을 통해 주소를 위도, 경도로 변환하는 두 방법을 살펴봤다. 필자는 결과적으로 카카오 맵 API를 선택해서 사용중이다. Nominatim의 경우 트래픽 초과로 인해 접속이 안되는 경우도 있었고 어차피 국내 주소를 사용할 예정이기 때문에 카카오가 더 정확하지 않을까 싶다. 본인의 상황에 맞게 사용하면 좋을 것 같다.