Upgrade to Pro — share decks privately, control downloads, hide ads and more …

streamlit-foliumで地図系APIをインタラクティブに可視化する

 streamlit-foliumで地図系APIをインタラクティブに可視化する

More Decks by NearMeの技術発表資料です

Transcript

  1. 1 まずは動かしてみよう Download: https://gist.github.com/kenji4569/b14ba47b1ec58fb2426fcc12f1bd777a Setup: $ pip install streamlit streamlit-folium

    $ streamlit run streamlit-folium-example-app.py (もし動かない場合は、Pythonのバージョンを上げてみてください)
  2. 4 コード解説:状態の初期化 if not st.session_state.get("initialized"): initial_waypoints = [HANEDA_T1, TOKYO] for

    i, waypoint in enumerate(initial_waypoints): st.session_state["waypoint_{0}_lat".format(i)] = waypoint[0] st.session_state["waypoint_{0}_lng".format(i)] = waypoint[1] st.session_state.initialized = True 次回から実行されない 状態の初期化
  3. 5 コード解説:サイドバーに数値入力を表示 with st.sidebar: for i, waypoint in enumerate(waypoints): st.write("Waypoint

    {0}".format(i)) col1, col2 = st.columns(2) with col1: st.number_input( "lat", value=waypoint[0], key="waypoint_{0}_lat".format(i), format=DEGREE_FORMAT, step=DEGREE_STEP, ) ... サイドバーに表示 2列に分けて表示 数値入力
  4. 6 コード解説:アクションボタン def on_remove_last_waypoint (): last_index = len(waypoints) - 1

    if last_index < 0: return st.session_state["waypoint_{0}_lat".format(last_index)] = None st.session_state["waypoint_{0}_lng".format(last_index)] = None st.button("Remove last waypoint" , on_click=on_remove_last_waypoint ) ボタン配置 状態更新
  5. 7 コード解説:地図クリック @st.cache_data(max_entries=3) def create_folium_map(waypoints): m = folium.Map(location=TOKYO, zoom_start=11) m.add_child(folium.LatLngPopup())

    ... return m st_map = st_folium(create_folium_map(waypoints)) if st_map.get("last_clicked"): last_clicked = st_map["last_clicked"] last_index = len(waypoints) - 1 st.session_state[ "waypoint_{0}_lat".format(last_index + 1)] = last_clicked["lat"] st.session_state[ "waypoint_{0}_lng".format(last_index + 1)] = last_clicked["lng"] st_map["last_clicked"] = None st.rerun() folium.LatLngPopup()でクリックした時に位置 情報を取得できる @st.cache_dataでレスポンスをキャッシュ (そうしないとなぜか地図要素が増えると 挙動がおかしくなるので ..) 引数(のハッシュ)がキャッシュのキーとなる 状態更新 位置情報の削除 スクリプトの再実行 位置情報が入る