2 분 소요

folium 라이브러리를 이용해서 지도에 지역 정보를 표시해보고, 지오코드 라이브러리를 이용해서 좌표와 주소를 변환해보자


간단히 전처리 후 지도에 표시

import pandas as pd

은평구

ep_sight = pd.read_excel('/content/drive/MyDrive/동아리_스터디_대외활동/GDSC/Solution_Challenge/은평구_.xls', sheet_name=0)
ep_culture_facility = pd.read_excel('/content/drive/MyDrive/동아리_스터디_대외활동/GDSC/Solution_Challenge/은평구_.xls', sheet_name=1)
ep_leports = pd.read_excel('/content/drive/MyDrive/동아리_스터디_대외활동/GDSC/Solution_Challenge/은평구_.xls', sheet_name=2)
cols = ['명칭', '주소', '위도', '경도', '개요']
ep_sight = ep_sight[cols]
ep_culture_facility = ep_culture_facility[cols]
ep_leports = ep_leports[cols]
ep_sight['분류'] = '관광지'
ep_culture_facility['분류'] = '문화시설'
ep_leports['분류'] = '레포츠'
ep = pd.concat([ep_sight, ep_culture_facility, ep_leports], 0).reset_index().drop(columns=['index'])
ep['지역'] = '은평구'
ep

image


강북구

gb_sight = pd.read_excel('/content/drive/MyDrive/동아리_스터디_대외활동/GDSC/Solution_Challenge/강북구_.xls', sheet_name=0)
gb_culture_facility = pd.read_excel('/content/drive/MyDrive/동아리_스터디_대외활동/GDSC/Solution_Challenge/강북구_.xls', sheet_name=1)
gb_leports = pd.read_excel('/content/drive/MyDrive/동아리_스터디_대외활동/GDSC/Solution_Challenge/강북구_.xls', sheet_name=2)
gb_sight = gb_sight[cols]
gb_culture_facility = gb_culture_facility[cols]
gb_leports = gb_leports[cols]
gb_sight['분류'] = '관광지'
gb_culture_facility['분류'] = '문화시설'
gb_leports['분류'] = '레포츠'
gb = pd.concat([gb_sight, gb_culture_facility, gb_leports], 0).reset_index().drop(columns=['index'])
gb['지역'] = '강북구'
gb

image


도봉구

db_sight = pd.read_excel('/content/drive/MyDrive/동아리_스터디_대외활동/GDSC/Solution_Challenge/도봉구_.xls', sheet_name=0)
db_culture_facility = pd.read_excel('/content/drive/MyDrive/동아리_스터디_대외활동/GDSC/Solution_Challenge/도봉구_.xls', sheet_name=1)
db_leports = pd.read_excel('/content/drive/MyDrive/동아리_스터디_대외활동/GDSC/Solution_Challenge/도봉구_.xls', sheet_name=2)
db_sight = db_sight[cols]
db_culture_facility = db_culture_facility[cols]
db_leports = db_leports[cols]
db_sight['분류'] = '관광지'
db_culture_facility['분류'] = '문화시설'
db_leports['분류'] = '레포츠'
db = pd.concat([db_sight, db_culture_facility, db_leports], 0).reset_index().drop(columns=['index'])
db['지역'] = '도봉구'

image


df = pd.concat([ep, db, gb], axis=0).reset_index().drop(columns=['index'])

image


지도 시각화

!pip install folium
import folium
  • location: 위도, 경도 좌표를 기준으로 지도 그리기

  • zoom_start: 확대의 정도 지정, 최대 18

# 위도
latitude = 37.643496
# 경도
longitude = 127.002844

m = folium.Map(location=[latitude, longitude],
               zoom_start=13
              )
m

image


마커 추가

  • location: 마커를 추가할 위도, 경도 좌표 입력

  • popup: 표기할 팝업 문구 지정 (클릭 시 표기되는 문구)

  • tooltip: 표기할 툴팁 지정 (마우스 오버 시 표기되는 문구)

folium.Marker([latitude, longitude],
              popup="근현대사기념관",
              tooltip="강북구 근현대사기념관").add_to(m)
m

image


icon: 마커 스타일 변경 1

folium.Marker([37.653806, 127.008488],
              popup="박을복자수박물관",
              tooltip="강북구 박을복자수박물관", 
              icon=folium.Icon('red', icon='star'),
             ).add_to(m)
m

image


icon: 마커 스타일 변경 2

folium.CircleMarker([37.63039338346, 127.02485810146],
                    color='tomato',
                    radius = 100, 
                    tooltip='강북구').add_to(m)
m

image


수집한 데이터 지도에 표시하기

from folium.plugins import MarkerCluster


m = folium.Map(
    location=[37.631777,	127.027389],
    zoom_start=15
)

coords = df[['Latitude', 'Longitude', '지역', '명칭']]


# marker_cluster = MarkerCluster().add_to(m)
def sep_color(region):
  if region == "강북구":
    return 'red',
  elif region == "은평구":
    return 'green'
  elif region == "도봉구":
    return 'blue'

for lat, long, region, name in zip(coords['Latitude'], coords['Longitude'], coords['지역'], coords['명칭'], ):
    color = sep_color(region)
    folium.Marker([lat, long], 
                  icon = folium.Icon(color=color), 
                  popup = name,
                  tooltip=region+' '+name).add_to(m)
m

image


df.to_csv('/content/drive/MyDrive/동아리_스터디_대외활동/GDSC/Solution_Challenge/final_data.csv', index=False)


주소, 좌표 변환하기

지오코드 API

주소 -> 좌표 변환

# 가입 없이 주소->좌표 변환
from geopy.geocoders import Nominatim

def geocoding(address):
    geolocoder = Nominatim(user_agent = 'South Korea', timeout=None)
    geo = geolocoder.geocode(address)
    crd = {"lat": str(geo.latitude), "lng": str(geo.longitude)}

    return crd

crd = geocoding("서울시 강북구 4.19로8길 17")
print(crd['lat'])
print(crd['lng'])
37.6468876
127.0086245


좌표 -> 주소 변환

# 가입 없이 좌표->주소 변환
from geopy.geocoders import Nominatim

def geocoding_reverse(lat_lng_str): 
    geolocoder = Nominatim(user_agent = 'South Korea', timeout=None)
    address = geolocoder.reverse(lat_lng_str)

    return address

address = geocoding_reverse('37.6468876, 127.0086245')
print(address)
우이동, 강북구, 서울, 01021, 대한민국


카카오API

주소 -> 좌표 변환

# 카카오API를 사용하여 주소->좌표 변환
import requests, json

def get_location(address):
  url = 'https://dapi.kakao.com/v2/local/search/address.json?query=' + address
  # 'KaKaoAK '는 그대로 두시고 개인키만 지우고 입력해 주세요.
  headers = {"Authorization": "KakaoAK 개인키"}
  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'])}
  address_name = address['address_name']

  return crd

crd = get_location("서울시 강북구 4.19로8길 17")
print(crd)
{'lat': '37.6483906662883', 'lng': '127.009071258248'}


주소 -> 좌표 변환

# 카카오API를 사용하여 좌표->주소 변환
import requests, json, pprint

def get_address(lat, lng):
    url = "https://dapi.kakao.com/v2/local/geo/coord2regioncode.json?x="+lng+"&y="+lat
    # 'KaKaoAK '는 그대로 두시고 개인키만 지우고 입력해 주세요.
    headers = {"Authorization": "KakaoAK 개인키"}
    api_json = requests.get(url, headers=headers)
    full_address = json.loads(api_json.text)

    return full_address

full_address = get_address('37.6483906662883', '127.009071258248')
pprint.pprint(full_address)
{'documents': [{'address_name': '서울특별시 강북구 수유동',
                'code': '1130510300',
                'region_1depth_name': '서울특별시',
                'region_2depth_name': '강북구',
                'region_3depth_name': '수유동',
                'region_4depth_name': '',
                'region_type': 'B',
                'x': 127.02209452076173,
                'y': 37.64246218415331},
               {'address_name': '서울특별시 강북구 우이동',
                'code': '1130564500',
                'region_1depth_name': '서울특별시',
                'region_2depth_name': '강북구',
                'region_3depth_name': '우이동',
                'region_4depth_name': '',
                'region_type': 'H',
                'x': 127.00189499221491,
                'y': 37.663269731120074}],
 'meta': {'total_count': 2}}

댓글남기기