0
0

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?

Streamlitで位置情報を取って表示する(streamlit-geolocation)

Posted at

やりたいこと

  • Streamlitアプリでの現在地(緯度・経度)を取得する
  • 取得した位置を地図にプロットして表示する

今回は、streamlit-geolocationを利用する。
内部的には、navigator.geolocation.getCurrentPosition()を参照している。

image.png

GPS情報を取得して表示すると自宅の位置が表示されるので、
サンプルとして「横浜ランドマークタワー」の位置情報を表示しています。

環境

Version
Python 3.12.9
Streamlit 1.52.1
streamlit-geolocation 0.0.10

コード記述

from streamlit_geolocation import streamlit_geolocation

location = streamlit_geolocation()

streamlit_geolocation() を呼ぶと、ブラウザ側で位置情報取得(Geolocation API) が走り、取得できた場合は 辞書(dict) 形式の位置情報が返ってくる。

streamlitのアプリ上では、位置情報ボタンが表示される。

image.png

位置情報を取得する際、ブラウザでのユーザの許可がないと取得できない。

コード全体

import streamlit as st
import pandas as pd
from streamlit_geolocation import streamlit_geolocation

st.title("Streamlit-geolocation")

# デモ用:横浜ランドマークタワー
DEMO_LOCATION = {
    "latitude": 35.454674,
    "longitude": 139.631488,
    "altitude": 0,
    "accuracy": 138,
    "altitudeAccuracy": 0,
    "heading": None,
    "speed": None,
}

use_real_location = st.toggle("実位置を使う", value=False)

if use_real_location:
    location = streamlit_geolocation()
    if not (isinstance(location, dict) and location.get("latitude") is not None):
        st.warning("位置情報が取得できませんでした。ブラウザで許可して再実行してください。")
        st.stop()
    label = "実位置"
else:
    location = DEMO_LOCATION
    label = "デモ位置(横浜ランドマークタワー)"

lat = float(location["latitude"])
lon = float(location["longitude"])

st.write(f"**{label}**: ({lat:.6f}, {lon:.6f})")
st.map(pd.DataFrame([{"lat": lat, "lon": lon}]), zoom=14)

st.subheader("取得したGPS情報(生データ)")
st.json(location)

0
0
0

Register as a new user and use Qiita more conveniently

  1. You get articles that match your needs
  2. You can efficiently read back useful information
  3. You can use dark theme
What you can do with signing up
0
0

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?