hail_html / index.html
andrewammann's picture
Update index.html
180a010 verified
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>Hail Size Estimator</title>
<script src="https://cdn.tailwindcss.com"></script>
<script src="https://cdn.jsdelivr.net/npm/react@18.2.0/umd/react.production.min.js"></script>
<script src="https://cdn.jsdelivr.net/npm/react-dom@18.2.0/umd/react-dom.production.min.js"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/babel-standalone/7.22.10/babel.min.js"></script>
<script src="https://cdn.jsdelivr.net/npm/axios@1.4.0/dist/axios.min.js"></script>
<script src="https://unpkg.com/@duckdb/duckdb-wasm@1.28.0/dist/duckdb-browser.js"></script>
<script src="https://unpkg.com/leaflet@1.9.4/dist/leaflet.js"></script>
<link rel="stylesheet" href="https://unpkg.com/leaflet@1.9.4/dist/leaflet.css" />
<style>
#map { height: 400px; }
.sidebar { width: 300px; }
</style>
</head>
<body class="bg-gray-100">
<div id="root"></div>
<script type="text/babel">
const { useState, useEffect } = React;
const App = () => {
const [address, setAddress] = useState("Dallas, TX");
const [date, setDate] = useState("2025-08-08");
const [showData, setShowData] = useState("Show All");
const [data, setData] = useState([]);
const [lat, setLat] = useState(null);
const [lon, setLon] = useState(null);
const [map, setMap] = useState(null);
const geocodeKey = process.env.GEOCODE_KEY || "YOUR_API_KEY";
const convertToCSV = (data) => {
const headers = ["Date_utc", "Within 1 Mile", "Within 3 Miles", "Within 5 Miles", "Within 10 Miles", "Address"];
const csvRows = [headers.join(",")];
data.forEach(row => {
const values = headers.map(header => {
return header === "Address" ? `"${address}"` : `"${row[header] || ""}"`;
});
csvRows.push(values.join(","));
});
return new Blob([csvRows.join("\n")], { type: "text/csv" });
};
const geocode = async (address) => {
try {
const encodedAddress = encodeURIComponent(address);
const response = await axios.get(
`https://api.geocod.io/v1.7/geocode?q=${encodedAddress}&api_key=${geocodeKey}`,
{ headers: { "Content-Type": "application/json" } }
);
const { lat, lng } = response.data.results[0].location;
setLat(lat);
setLon(lng);
return { lat, lng };
} catch (error) {
alert("Address not found. Try correcting with City, State & Zip.");
return { lat: null, lng: null };
}
};
const getData = async (lat, lon, dateStr) => {
const db = await duckdb.createDB();
await db.run("PRAGMA threads=2");
await db.run("PRAGMA enable_object_cache");
const query = `
SELECT "#ZTIME" AS Date_utc, LON, LAT, MAXSIZE
FROM 'data/*.parquet'
WHERE LAT <= ${lat + 1} AND LAT >= ${lat - 1}
AND LON <= ${lon + 1} AND LON >= ${lon - 1}
AND "#ZTIME" <= '${dateStr}'
`;
const result = await db.query(query);
return result.toArray();
};
const calculateDistance = (lat1, lon1, lat2, lon2) => {
const toRad = (value) => (value * Math.PI) / 180;
const R = 3958.8; // Earth's radius in miles
const dLat = toRad(lat2 - lat1);
const dLon = toRad(lon2 - lon1);
const a = Math.sin(dLat / 2) * Math.sin(dLat / 2) +
Math.cos(toRad(lat1)) * Math.cos(toRad(lat2)) *
Math.sin(dLon / 2) * Math.sin(dLon / 2);
const c = 2 * Math.atan2(Math.sqrt(a), Math.sqrt(1 - a));
return R * c;
};
useEffect(() => {
const initializeMap = (lat, lon) => {
const mapInstance = L.map("map").setView([lat, lon], 9);
L.tileLayer("https://{s}.tile.openstreetmap.org/{z}/{x}/{y}.png", {
attribution: '&copy; <a href="https://www.openstreetmap.org/copyright">OpenStreetMap</a>'
}).addTo(mapInstance);
L.marker([lat, lon]).addTo(mapInstance)
.bindTooltip(`Address: ${address}`);
setMap(mapInstance);
};
const fetchData = async () => {
const { lat, lng } = await geocode(address);
if (lat && lng) {
const dateStr = date.replace(/-/g, "");
let hailData = await getData(lat, lng, dateStr);
hailData = hailData.map(row => ({
...row,
Lat_address: lat,
Lon_address: lng,
Miles_to_Hail: calculateDistance(row.LAT, row.LON, lat, lng).toFixed(2),
MAXSIZE: Number(row.MAXSIZE).toFixed(2),
Category: row.Miles_to_Hail < 1 ? "Within 1 Mile" :
row.Miles_to_Hail < 3 ? "Within 3 Miles" :
row.Miles_to_Hail < 5 ? "Within 5 Miles" :
row.Miles_to_Hail < 10 ? "Within 10 Miles" : "Other"
}));
const pivotData = {};
hailData.forEach(row => {
if (!pivotData[row.Date_utc]) {
pivotData[row.Date_utc] = {};
}
pivotData[row.Date_utc][row.Category] = Math.max(
pivotData[row.Date_utc][row.Category] || 0,
row.MAXSIZE
);
});
const colsFocus = ["Within 1 Mile", "Within 3 Miles", "Within 5 Miles", "Within 10 Miles"];
let formattedData = Object.keys(pivotData).map(date => {
const row = { Date_utc: new Date(date).toISOString().split("T")[0] };
colsFocus.forEach(col => {
row[col] = pivotData[date][col] || null;
});
return row;
});
if (showData !== "Show All") {
formattedData = formattedData.filter(row => row[`Within ${showData}`]);
}
colsFocus.forEach((col, i) => {
if (i < colsFocus.length - 1) {
formattedData = formattedData.map(row => ({
...row,
[colsFocus[i + 1]]: row[colsFocus[i + 1]] && row[colsFocus[i + 1]] > (row[colsFocus[i]] || 0)
? row[colsFocus[i + 1]]
: row[colsFocus[i]]
}));
}
});
formattedData.sort((a, b) => new Date(b.Date_utc) - new Date(a.Date_utc));
setData(formattedData);
initializeMap(lat, lng);
}
};
fetchData();
}, [address, date, showData]);
return (
<div className="flex h-screen">
<div className="sidebar bg-white p-6 shadow-md">
<h2 className="text-xl font-bold mb-4">Hail Size Estimator</h2>
<div className="mb-4">
<label className="block text-sm font-medium">Address</label>
<input
type="text"
value={address}
onChange={(e) => setAddress(e.target.value)}
className="mt-1 p-2 w-full border rounded"
/>
</div>
<div className="mb-4">
<label className="block text-sm font-medium">Loss Date (Max)</label>
<input
type="date"
value={date}
max="2025-08-08"
onChange={(e) => setDate(e.target.value)}
className="mt-1 p-2 w-full border rounded"
/>
</div>
<div className="mb-4">
<label className="block text-sm font-medium">Show Data Within</label>
<select
value={showData}
onChange={(e) => setShowData(e.target.value)}
className="mt-1 p-2 w-full border rounded"
>
<option>Show All</option>
<option>1 Mile</option>
<option>3 Miles</option>
<option>5 Miles</option>
</select>
</div>
</div>
<div className="flex-1 p-6">
<div className="flex gap-6">
<div className="w-3/5">
<h2 className="text-xl font-bold mb-4">Estimated Maximum Hail Size</h2>
<p className="text-sm mb-4">Data from 2010 to 2025-08-08</p>
<table className="w-full border-collapse">
<thead>
<tr className="bg-gray-200">
<th className="border p-2">Date</th>
<th className="border p-2">Within 1 Mile</th>
<th className="border p-2">Within 3 Miles</th>
<th className="border p-2">Within 5 Miles</th>
<th className="border p-2">Within 10 Miles</th>
</tr>
</thead>
<tbody>
{data.map((row, index) => (
<tr key={index} className="border">
<td className="border p-2">{row.Date_utc}</td>
<td className="border p-2">{row["Within 1 Mile"] || "-"}</td>
<td className="border p-2">{row["Within 3 Miles"] || "-"}</td>
<td className="border p-2">{row["Within 5 Miles"] || "-"}</td>
<td className="border p-2">{row["Within 10 Miles"] || "-"}</td>
</tr>
))}
</tbody>
</table>
<a
href={URL.createObjectURL(convertToCSV(data))}
download={`${address}_${date.replace(/-/g, "")}.csv`}
className="mt-4 inline-block bg-blue-500 text-white px-4 py-2 rounded"
>
Download Data as CSV
</a>
</div>
<div className="w-2/5">
<h2 className="text-xl font-bold mb-4">Map</h2>
<div id="map" className="w-full"></div>
</div>
</div>
</div>
</div>
);
};
ReactDOM.render(<App />, document.getElementById("root"));
</script>
</body>
</html>