software_development:python_folium_map

Differences

This shows you the differences between two versions of the page.

Link to this comparison view

Next revision
Previous revision
software_development:python_folium_map [2020/04/27 02:17] – created prgramsoftware_development:python_folium_map [2025/07/07 14:12] (current) – external edit 127.0.0.1
Line 5: Line 5:
  
  
-행정동 경계 그리+=== map 생성, 초화 === 
 +<code python> 
 +import folium 
 +m = folium.Map(location=[37.6, 127], tiles="OpenStreetMap", zoom_start=13) 
 +</code>
  
  
-MarkerCircle+===행정동 경계 그리기=== 
 +https://github.com/vuski/admdongkor 
 +[[data_analysis:work:korea_address_system]] 
 +geojson 이용 
 +<code python> 
 +nodeData = 'C:\\Users\\~~~\\Downloads\\HangJeongDong_ver20200401.geojson' 
 +nodeData = open(nodeDataencoding = "utf-8").read()
  
-FastMarkerCluster+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)
 +</code>
 +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)==
 +<code python>
 +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)
 +</code>
 +li,col : dv_nm 에 따라 색을 다르게 함
 +
 +==Marker==
 +<code python>
 +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)
 +</code>
 +    
 +===Marker Cluster ===
 +Zoom에 따라서 Cluster 를 만들어줌
 +<code python>
 +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'))
 +</code>
 +
 +===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에서 직접 실행해서 더 빠름
 +
 +<code python>
 +from folium.plugins import FastMarkerCluster
 +</code>
 +
 +==Circle==
 +<code python>
 +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 = $(`<div id='mytext' class='display_text' style='width: 100.0%; height: 100.0%;'> ${display_text.text}</div>`)[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))
 +</code>
 +
 +==Marker ==
 +<code python>
 +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 = $(`<div id='mytext' class='display_text' style='width: 100.0%; height: 100.0%;'> ${display_text.text}</div>`)[0];"
 +            "popup.setContent(mytext);"
 +            "marker.bindPopup(popup);"
 +            'return marker};')
 +m.add_child(FastMarkerCluster(df[['y_codn', 'x_codn', 'nm']].dropna().values.tolist(), callback=callback))
 +</code>
 +row[0,1,2] 를 사용
 +popup
 +
 +===map 저장===
 +
 +<code python>
 +m.save(os.path.join('', 'map.html'))
 +</code>
  
 {{tag>software_development python folium 지도그리기}} {{tag>software_development python folium 지도그리기}}
  • software_development/python_folium_map.1587953876.txt.gz
  • Last modified: 2025/07/07 14:13
  • (external edit)