I want to create a heatmap on map using st_folium. I also want to generate data to display in a function that should run in thread and generate data every 10 seconds.
How do I make the function generated data in a parallel process to be displayed on the map?
here the code I have build till now:
import random
import folium
from folium.plugins import HeatMap
import streamlit as st
from streamlit_folium import st_folium
import queue
import numpy as np
import pandas as pd
import time
import threading
st.set_page_config(layout="wide")
CENTER_START = [39.949610, -75.150282]
ZOOM_START = 8
if "center" not in st.session_state:
st.session_state["center"] = [39.949610, -75.150282]
if "zoom" not in st.session_state:
st.session_state["zoom"] = 8
if "heat_data" not in st.session_state:
st.session_state["heat_data"] = []
col1, col2, col3 = st.columns(3)
q = queue.Queue()
if col1.button("Shift center"):
random_shift_y = (random.random() - 0.5) * 0.3
random_shift_x = (random.random() - 0.5) * 0.3
st.session_state["center"] = [
st.session_state["center"][0] + random_shift_y,
st.session_state["center"][1] + random_shift_x,
]
if col2.button("Shift zoom"):
st.session_state["zoom"] = st.session_state["zoom"] + 1
if st.session_state["zoom"] >= 10:
st.session_state["zoom"] = 5
if col3.button("Add random data point"):
random_lat = random.random() * 0.5 + 39.8
random_lon = random.random() * 0.5 - 75.2
st.session_state["heat_data"].append([random_lat, random_lon])
q.put([random_lat, random_lon])
"# New method"
"### Pass `center`, `zoom`, and `feature_group_to_add` to `st_folium`"
def generate_dataframe():
count = 0
while True:
num_rows= 10
munich_lat, munich_lon = 39.949610, -75.150282
lat_range = 0.1 # 0.1 degrees ~ approximately 11 km
lon_range = 0.1 # 0.1 degrees ~ approximately 7.5 km
# Generate random Magnitude values between 1 and 100
magnitude_values = np.random.randint(1, 101, size=num_rows)
# Generate random Latitude and Longitude values within the defined range
lat_values = np.random.uniform(munich_lat - lat_range / 2, munich_lat + lat_range / 2, size=num_rows)
lon_values = np.random.uniform(munich_lon - lon_range / 2, munich_lon + lon_range / 2, size=num_rows)
# Create DataFrame with Magnitude, Latitude, and Longitude
data = {
'Magnitude': magnitude_values,
'lat': lat_values,
'lon': lon_values
}
df = pd.DataFrame(data)
q.put(df)
count= count+1
print("generate ", count)
time.sleep(10)
is_exit_target_if_main_exits = True
st.session_state["is_generated"] = True
threading.Thread(
target=generate_dataframe,
daemon=is_exit_target_if_main_exits).start()
m = folium.Map(location=CENTER_START, zoom_start=8)
fg = folium.FeatureGroup(name="HeatMap")
heat_data = st.session_state["heat_data"]
print(q.get())
if heat_data:
HeatMap(heat_data).add_to(fg)
st_folium(
m,
center=st.session_state["center"],
zoom=st.session_state["zoom"],
key="new",
feature_group_to_add=fg,
height=400,
width=900,
)