-
Notifications
You must be signed in to change notification settings - Fork 4
Description
from flask import Flask, render_template_string, request
import requests
from datetime import datetime
app = Flask(name)
import os
API_KEY = os.environ.get("API_KEY") or "YOUR_OPENWEATHERMAP_API_KEY"
HTML = """
<title>Ultimate Global Weather Mobile</title> <script src="https://cdn.jsdelivr.net/npm/chart.js"></script> <style> body { margin:0; font-family: Arial,sans-serif; background:#0072ff; color:white; } body.light { background:linear-gradient(to right,#e0f7fa,#ffffff); color:black; } .container { width:90%; max-width:1200px; margin:auto; padding:20px; text-align:center; } h1 { margin-bottom:10px; font-size:1.8em; } input { padding:10px; width:200px; border-radius:5px; border:none; margin-bottom:5px; } button { padding:10px 20px; border-radius:5px; border:none; background:orange; cursor:pointer; font-weight:bold; } button:hover { background:#e68900; } #map { height:400px; margin-top:20px; border-radius:15px; } .leaflet-popup-content { text-align:center; max-width:200px; } #toggle { margin-top:10px; cursor:pointer; padding:5px 10px; background:#fff; color:#0072ff; border-radius:5px; display:inline-block; } .forecast-cards { display:flex; overflow-x:auto; padding:10px 0; gap:10px; margin-top:10px; } .forecast-card { min-width:80px; background:rgba(255,255,255,0.2); border-radius:10px; padding:5px; text-align:center; flex-shrink:0; } .forecast-card img { width:40px; height:40px; } @media(max-width:600px){ input{width:150px;} } </style>🌍 Ultimate Global Weather Map
Auto-refresh every 5 minutes ⏱️
Show Weather${city.city}
${city.temp}°C
${city.description}
7-Day Forecast
${forecastHTML}`; marker.bindPopup(popupContent).on('popupopen',function(){ var ctx=document.getElementById('chart-'+city.city).getContext('2d'); new Chart(ctx,{type:'line',data:{labels:city.forecast.map(d=>d.date),datasets:[{label:'Temp (°C)',data:city.forecast.map(d=>d.temp),borderColor:'orange',backgroundColor:'rgba(255,165,0,0.3)',tension:0.3}]},options:{responsive:true,maintainAspectRatio:false}}); }); } }); // User geolocation if(navigator.geolocation){ navigator.geolocation.getCurrentPosition(pos=>{ var lat=pos.coords.latitude; var lon=pos.coords.longitude; fetch(`/geo_weather?lat=${lat}&lon=${lon}`).then(res=>res.json()).then(city=>{ var icon=L.divIcon({html:``}); var marker=L.marker([city.lat,city.lon],{icon:icon}).addTo(map); map.setView([city.lat,city.lon],5); var forecastHTML=''; var popupContent=`${city.city} (You)
${city.temp}°C
${city.description}
7-Day Forecast
${forecastHTML}`; marker.bindPopup(popupContent).on('popupopen',function(){ var ctx=document.getElementById('chart-'+city.city).getContext('2d'); new Chart(ctx,{type:'line',data:{labels:city.forecast.map(d=>d.date),datasets:[{label:'Temp (°C)',data:city.forecast.map(d=>d.temp),borderColor:'purple',backgroundColor:'rgba(128,0,128,0.3)',tension:0.3}]},options:{responsive:true,maintainAspectRatio:false}}); }); }); }); } setTimeout(()=>location.reload(),300000); function toggleMode(){document.body.classList.toggle('light');} </script> """def get_weather(city):
geo=requests.get(f"http://api.openweathermap.org/geo/1.0/direct?q={city}&limit=1&appid={API_KEY}").json()
if not geo: return {"error":"City not found"}
lat,lon=geo[0]["lat"],geo[0]["lon"]
data=requests.get(f"https://api.openweathermap.org/data/2.5/onecall?lat={lat}&lon={lon}&units=metric&exclude=minutely,hourly,alerts&appid={API_KEY}").json()
forecast=[]
for day in data["daily"][:7]: forecast.append({"date":datetime.utcfromtimestamp(day["dt"]).strftime("%a"),"temp":round(day["temp"]["day"]),"icon":day["weather"][0]["icon"]})
return {"city":city.title(),"lat":lat,"lon":lon,"temp":round(data["current"]["temp"]),"description":data["current"]["weather"][0]["description"].title(),"icon":data["current"]["weather"][0]["icon"],"forecast":forecast}
@app.route("/",methods=["GET","POST"])
def index():
weather=[]
if request.method=="POST":
cities=request.form["cities"].split(",")
weather=[get_weather(c.strip()) for c in cities]
return render_template_string(HTML,weather=weather)
@app.route("/geo_weather")
def geo_weather():
lat=float(request.args.get("lat"))
lon=float(request.args.get("lon"))
data=requests.get(f"https://api.openweathermap.org/data/2.5/onecall?lat={lat}&lon={lon}&units=metric&exclude=minutely,hourly,alerts&appid={API_KEY}").json()
forecast=[]
for day in data["daily"][:7]: forecast.append({"date":datetime.utcfromtimestamp(day["dt"]).strftime("%a"),"temp":round(day["temp"]["day"]),"icon":day["weather"][0]["icon"]})
return {"city":"Your Location","lat":lat,"lon":lon,"temp":round(data["current"]["temp"]),"description":data["current"]["weather"][0]["description"].title(),"icon":data["current"]["weather"][0]["icon"],"forecast":forecast}
if name=="main":
app.run(host="0.0.0.0", port=10000)