====== python folium ======
지도 그리기
https://mkjjo.github.io/python/2019/08/18/korea_population.html
=== map 생성, 초기화 ===
import folium
m = folium.Map(location=[37.6, 127], tiles="OpenStreetMap", zoom_start=13)
===행정동 경계 그리기===
https://github.com/vuski/admdongkor
[[data_analysis:work:korea_address_system]]
geojson 이용
nodeData = 'C:\\Users\\~~~\\Downloads\\HangJeongDong_ver20200401.geojson'
nodeData = open(nodeData, encoding = "utf-8").read()
import json
nodes = json.loads(nodeData)
geo_json = folium.GeoJson(nodeData, tooltip=folium.GeoJsonTooltip(fields=['adm_nm']))
geo_json = folium.GeoJson(nodes, tooltip=folium.GeoJsonTooltip(fields=['adm_nm']), smooth_factor=10)
geo_json.add_to(m)
line 7-8: string이나 json으로 변환된 변수나 모두 적용가능
smooth_factor 값이 크면, performance 상승(smoothness와 trade-off) (([https://github.com/python-visualization/folium/issues/951|github]]))
GeoJsonTooltip 에 Series 를 넣으면 자동으로 tooltip 생성
GeoJsonPopUp 은 버전 때문에 안되는듯?
===Marker, Circle===
==Circle (bubble)==
from tqdm import tqdm
for x in tqdm(dcd):
for i,l in enumerate(li):
tmp = df[df.dv_nm==l][df.admin_dcd==x]
lat = tmp['y_codn'].mean()
lon = tmp['x_codn'].mean()
count = len(tmp)
if pd.isnull(lat) or pd.isnull(lon):
continue
folium.CircleMarker((lat,lon), radius=count / 5, color=col[i], fill_color=col[i], popup=count).add_to(m)
folium.LayerControl(collapsed=False).add_to(m)
li,col : dv_nm 에 따라 색을 다르게 함
==Marker==
from tqdm import tqdm
for x in tqdm(range(len(df))):
if df.iloc[x,:]['dv_nm'] == '@@':
color = 'blue'
elif df.iloc[x,:]['dv_nm'] == '##':
color = 'red'
location = (latitude[x], longitude[x])
folium.Marker(location, popup=df.iloc[x,:]['nm'], icon=folium.Icon(color=color)).add_to(m)
===Marker Cluster ===
Zoom에 따라서 Cluster 를 만들어줌
from folium.plugins import MarkerCluster
mc = MarkerCluster()
for i,row in tqdm(df_store.iterrows()):
lat = row['y_codn']
lon = row['x_codn']
if math.isnan(lat) or math.isnan(lon):
continue
#folium.Marker((lat,lon), popup=row['pos_nm'], icon=folium.Icon(color='blue')).add_to(m)
mc.add_child(folium.Marker(location=[lat,lon], popup=row['pos_nm']))
m.add_child(mc)
# Save to html
m.save(os.path.join('', 'map.html'))
===FastMarkerCluster===
https://medium.com/@bobhaffner/folium-markerclusters-and-fastmarkerclusters-1e03b01cb7b1
https://www.reddit.com/r/learnpython/comments/bg6w3f/hey_guys_im_struggling_to_create_a_geojson/
https://python-visualization.github.io/folium/quickstart.html#Markers
zoom 에 따라서 Cluster 를 만들어줌.
Fast는 javascript에서 직접 실행해서 더 빠름
from folium.plugins import FastMarkerCluster
==Circle==
callback = ("""function (row) {
var circle = L.circle(new L.LatLng(row[0], row[1]), {color: "blue", radius: row[2]});
var popup = L.popup({maxWidth: '300'});
const display_text = {text: row[2]};
var mytext = $(` ${display_text.text}
`)[0];
popup.setContent(mytext);
circle.bindPopup(popup);
return circle;
};""")
m.add_child(FastMarkerCluster(df[df.dv_nm==li[1]][['y_codn', 'x_codn','count']].values.tolist(), callback=callback))
==Marker ==
callback = ('function (row) {'
'var marker = L.marker(new L.LatLng(row[0], row[1]), {color: "blue"});'
'var icon = L.AwesomeMarkers.icon({'
"icon: 'info-sign',"
"iconColor: 'white',"
"markerColor: 'blue',"
"prefix: 'glyphicon',"
"extraClasses: 'fa-rotate-0'"
'});'
'marker.setIcon(icon);'
"var popup = L.popup({maxWidth: '300'});"
"const display_text = {text: row[2]};"
"var mytext = $(` ${display_text.text}
`)[0];"
"popup.setContent(mytext);"
"marker.bindPopup(popup);"
'return marker};')
m.add_child(FastMarkerCluster(df[['y_codn', 'x_codn', 'nm']].dropna().values.tolist(), callback=callback))
row[0,1,2] 를 사용
popup
===map 저장===
m.save(os.path.join('', 'map.html'))
{{tag>software_development python folium 지도그리기}}
~~DISCUSSION~~