I am very new python. And I am struggling to auto refresh markers using dash leaflet. Code refreshes popup of marker, gets updated data from data base in interval time as expected. But color of markers are not refreshing. Only hard refresh of the page helps. I also have tried to refresh whole page with no success, same behaviour
How to fix the code to auto refresh markers on page?
import json
import dash
import dash_leaflet as dl
from dash import html, dcc
from dash.dependencies import Input, Output
import psycopg2
from database import DATABASE_CONFIG
from datetime import datetime
app = dash.Dash(__name__)
query = """
select
name, latitude, longitude,
case
when ss <= 3600 then 'green'
when ss > 3600 and ss <= 86400 then 'orange'
else 'red'
end as type
from (
select
city.name, city.latitude, city.longitude, EXTRACT(EPOCH FROM (now() - max(dat."updateTime"))) as ss
from
public."microController" mic
left join public."mainData" dat on mic."controllerID" = dat."controllerID"
join public."dictCity" city on mic."cityId" = city.id
where
mic."isDeleted" = false
group by mic."cityId", city.name, city.latitude, city.longitude
) t
"""
def get_city_data():
try:
conn = psycopg2.connect(**DATABASE_CONFIG)
cur = conn.cursor()
cur.execute(query)
cities = cur.fetchall()
cur.close()
conn.close()
return cities
except Exception as e:
return []
with open("countries.geojson", encoding='utf-8') as f:
geojson_data = json.load(f)
country_feature = None
for feature in geojson_data['features']:
if feature['properties'].get('ADMIN') == 'Kazakhstan':
country_feature = feature
break
if not country_feature:
raise ValueError("Failed to find country in GeoJSON data")
app.layout = html.Div([
dl.Map(
id='map',
style={'width': '100%', 'height': '100vh'},
center=[48.0, 68.0],
zoom=5,
children=[
dl.TileLayer(),
dl.GeoJSON(id='geojson', data=country_feature),
dl.LayerGroup(id='city-markers')
]
),
dcc.Interval(
id='interval-component',
interval=5 * 1000,
n_intervals=0
)
])
@app.callback(
Output('city-markers', 'children'),
Input('interval-component', 'n_intervals')
)
def update_map(n_intervals):
city_data = get_city_data()
if not city_data:
return []
current_time = datetime.now().strftime("%H:%M:%S")
city_circles = [
dl.CircleMarker(
center=[city[1], city[2]],
radius=10,
color='black',
fillColor=city[3],
fillOpacity=0.6,
stroke=True,
children=[dl.Popup(f"{city[0]} - updated at {current_time}")]
)
for city in city_data
]
return city_circles
if __name__ == '__main__':
app.
run_server(debug=True)