<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>GeoStream Engine - Geospatial Processing</title>
<style>
* {
margin: 0;
padding: 0;
box-sizing: border-box;
}
:root {
--bg-primary: #0a0f1a;
--bg-secondary: #111827;
--bg-tertiary: #1e293b;
--accent-cyan: #00d4ff;
--accent-orange: #ff6b35;
--accent-green: #10b981;
--accent-purple: #a855f7;
--accent-yellow: #fbbf24;
--text-primary: #f1f5f9;
--text-secondary: #94a3b8;
--border-color: #334155;
}
body {
font-family: 'Segoe UI', system-ui, sans-serif;
background: var(--bg-primary);
color: var(--text-primary);
overflow: hidden;
height: 100vh;
}
.app-container {
display: grid;
grid-template-columns: 320px 1fr 300px;
grid-template-rows: 60px 1fr;
height: 100vh;
gap: 1px;
background: var(--border-color);
}
.header {
grid-column: 1 / -1;
background: linear-gradient(135deg, var(--bg-secondary) 0%, var(--bg-tertiary) 100%);
display: flex;
align-items: center;
justify-content: space-between;
padding: 0 24px;
border-bottom: 1px solid var(--border-color);
}
.logo {
display: flex;
align-items: center;
gap: 12px;
}
.logo-icon {
width: 36px;
height: 36px;
background: linear-gradient(135deg, var(--accent-cyan), var(--accent-purple));
border-radius: 8px;
display: flex;
align-items: center;
justify-content: center;
}
.logo-text {
font-size: 20px;
font-weight: 700;
letter-spacing: -0.5px;
}
.logo-text span {
color: var(--accent-cyan);
}
.header-stats {
display: flex;
gap: 32px;
}
.stat-item {
text-align: center;
}
.stat-value {
font-size: 18px;
font-weight: 700;
color: var(--accent-cyan);
}
.stat-label {
font-size: 11px;
color: var(--text-secondary);
text-transform: uppercase;
letter-spacing: 0.5px;
}
.left-panel {
background: var(--bg-secondary);
overflow-y: auto;
padding: 16px;
}
.map-container {
background: var(--bg-primary);
position: relative;
overflow: hidden;
}
.right-panel {
background: var(--bg-secondary);
overflow-y: auto;
padding: 16px;
}
.panel-section {
margin-bottom: 20px;
}
.section-title {
font-size: 12px;
font-weight: 600;
color: var(--text-secondary);
text-transform: uppercase;
letter-spacing: 1px;
margin-bottom: 12px;
padding-bottom: 8px;
border-bottom: 1px solid var(--border-color);
}
.control-group {
margin-bottom: 16px;
}
.control-label {
font-size: 12px;
color: var(--text-secondary);
margin-bottom: 6px;
display: block;
}
.control-input {
width: 100%;
padding: 10px 12px;
background: var(--bg-tertiary);
border: 1px solid var(--border-color);
border-radius: 6px;
color: var(--text-primary);
font-size: 13px;
transition: border-color 0.2s;
}
.control-input:focus {
outline: none;
border-color: var(--accent-cyan);
}
.control-select {
width: 100%;
padding: 10px 12px;
background: var(--bg-tertiary);
border: 1px solid var(--border-color);
border-radius: 6px;
color: var(--text-primary);
font-size: 13px;
cursor: pointer;
}
.btn {
width: 100%;
padding: 12px 16px;
border: none;
border-radius: 6px;
font-size: 13px;
font-weight: 600;
cursor: pointer;
transition: all 0.2s;
margin-bottom: 8px;
}
.btn-primary {
background: linear-gradient(135deg, var(--accent-cyan), #0099cc);
color: var(--bg-primary);
}
.btn-primary:hover {
transform: translateY(-1px);
box-shadow: 0 4px 12px rgba(0, 212, 255, 0.3);
}
.btn-secondary {
background: var(--bg-tertiary);
color: var(--text-primary);
border: 1px solid var(--border-color);
}
.btn-secondary:hover {
border-color: var(--accent-cyan);
}
.btn-danger {
background: linear-gradient(135deg, #ef4444, #dc2626);
color: white;
}
#mapCanvas {
width: 100%;
height: 100%;
cursor: grab;
}
#mapCanvas:active {
cursor: grabbing;
}
.map-overlay {
position: absolute;
top: 16px;
left: 16px;
display: flex;
flex-direction: column;
gap: 8px;
}
.map-btn {
width: 40px;
height: 40px;
background: var(--bg-secondary);
border: 1px solid var(--border-color);
border-radius: 6px;
color: var(--text-primary);
cursor: pointer;
display: flex;
align-items: center;
justify-content: center;
font-size: 18px;
transition: all 0.2s;
}
.map-btn:hover {
background: var(--bg-tertiary);
border-color: var(--accent-cyan);
}
.coords-display {
position: absolute;
bottom: 16px;
left: 16px;
background: rgba(17, 24, 39, 0.9);
padding: 10px 14px;
border-radius: 6px;
font-size: 12px;
font-family: 'Consolas', monospace;
border: 1px solid var(--border-color);
}
.coords-display span {
color: var(--accent-cyan);
}
.zoom-display {
position: absolute;
bottom: 16px;
right: 16px;
background: rgba(17, 24, 39, 0.9);
padding: 10px 14px;
border-radius: 6px;
font-size: 12px;
border: 1px solid var(--border-color);
}
.metric-card {
background: var(--bg-tertiary);
border-radius: 8px;
padding: 14px;
margin-bottom: 10px;
border: 1px solid var(--border-color);
}
.metric-header {
display: flex;
justify-content: space-between;
align-items: center;
margin-bottom: 8px;
}
.metric-title {
font-size: 12px;
color: var(--text-secondary);
}
.metric-value {
font-size: 20px;
font-weight: 700;
}
.metric-value.cyan { color: var(--accent-cyan); }
.metric-value.green { color: var(--accent-green); }
.metric-value.orange { color: var(--accent-orange); }
.metric-value.purple { color: var(--accent-purple); }
.metric-bar {
height: 4px;
background: var(--bg-secondary);
border-radius: 2px;
overflow: hidden;
margin-top: 8px;
}
.metric-bar-fill {
height: 100%;
border-radius: 2px;
transition: width 0.3s;
}
.worker-list {
display: flex;
flex-direction: column;
gap: 8px;
}
.worker-item {
background: var(--bg-tertiary);
border-radius: 6px;
padding: 10px 12px;
display: flex;
align-items: center;
gap: 10px;
border: 1px solid var(--border-color);
}
.worker-status {
width: 8px;
height: 8px;
border-radius: 50%;
animation: pulse 2s infinite;
}
.worker-status.active {
background: var(--accent-green);
}
.worker-status.busy {
background: var(--accent-orange);
}
.worker-status.idle {
background: var(--text-secondary);
}
@keyframes pulse {
0%, 100% { opacity: 1; }
50% { opacity: 0.5; }
}
.worker-info {
flex: 1;
}
.worker-name {
font-size: 12px;
font-weight: 600;
}
.worker-load {
font-size: 10px;
color: var(--text-secondary);
}
.tile-grid {
display: grid;
grid-template-columns: repeat(4, 1fr);
gap: 4px;
margin-top: 12px;
}
.tile-cell {
aspect-ratio: 1;
background: var(--bg-tertiary);
border-radius: 3px;
font-size: 9px;
display: flex;
align-items: center;
justify-content: center;
transition: all 0.2s;
border: 1px solid transparent;
}
.tile-cell.cached {
background: rgba(16, 185, 129, 0.3);
border-color: var(--accent-green);
}
.tile-cell.loading {
background: rgba(0, 212, 255, 0.2);
border-color: var(--accent-cyan);
animation: tileLoad 0.5s infinite;
}
@keyframes tileLoad {
0%, 100% { opacity: 1; }
50% { opacity: 0.5; }
}
.stream-viz {
height: 120px;
background: var(--bg-tertiary);
border-radius: 6px;
margin-top: 12px;
overflow: hidden;
position: relative;
border: 1px solid var(--border-color);
}
#streamCanvas {
width: 100%;
height: 100%;
}
.legend {
display: flex;
gap: 16px;
margin-top: 12px;
flex-wrap: wrap;
}
.legend-item {
display: flex;
align-items: center;
gap: 6px;
font-size: 11px;
}
.legend-color {
width: 12px;
height: 12px;
border-radius: 3px;
}
.transform-preview {
background: var(--bg-tertiary);
border-radius: 6px;
padding: 12px;
margin-top: 12px;
font-family: 'Consolas', monospace;
font-size: 11px;
border: 1px solid var(--border-color);
}
.transform-row {
display: flex;
justify-content: space-between;
margin-bottom: 6px;
}
.transform-label {
color: var(--text-secondary);
}
.transform-value {
color: var(--accent-cyan);
}
.log-container {
background: var(--bg-tertiary);
border-radius: 6px;
padding: 10px;
max-height: 200px;
overflow-y: auto;
font-family: 'Consolas', monospace;
font-size: 10px;
border: 1px solid var(--border-color);
}
.log-entry {
margin-bottom: 4px;
padding: 4px 6px;
border-radius: 3px;
}
.log-entry.info {
background: rgba(0, 212, 255, 0.1);
border-left: 2px solid var(--accent-cyan);
}
.log-entry.success {
background: rgba(16, 185, 129, 0.1);
border-left: 2px solid var(--accent-green);
}
.log-entry.warn {
background: rgba(251, 191, 36, 0.1);
border-left: 2px solid var(--accent-yellow);
}
.log-time {
color: var(--text-secondary);
margin-right: 8px;
}
.range-container {
display: flex;
align-items: center;
gap: 10px;
}
.range-input {
flex: 1;
-webkit-appearance: none;
height: 6px;
background: var(--bg-tertiary);
border-radius: 3px;
outline: none;
}
.range-input::-webkit-slider-thumb {
-webkit-appearance: none;
width: 16px;
height: 16px;
background: var(--accent-cyan);
border-radius: 50%;
cursor: pointer;
}
.range-value {
min-width: 40px;
text-align: right;
font-size: 12px;
color: var(--accent-cyan);
}
.particle-container {
position: absolute;
top: 0;
left: 0;
width: 100%;
height: 100%;
pointer-events: none;
overflow: hidden;
}
.data-particle {
position: absolute;
width: 4px;
height: 4px;
background: var(--accent-cyan);
border-radius: 50%;
opacity: 0;
animation: particleFlow 3s linear infinite;
}
@keyframes particleFlow {
0% { opacity: 0; transform: translateX(-100px); }
10% { opacity: 1; }
90% { opacity: 1; }
100% { opacity: 0; transform: translateX(calc(100% + 100px)); }
}
</style>
</head>
<body>
<div class="app-container">
<header class="header">
<div class="logo">
<div class="logo-icon">
<svg width="20" height="20" viewBox="0 0 24 24" fill="none" stroke="white" stroke-width="2">
<circle cx="12" cy="12" r="10"/>
<path d="M2 12h20"/>
<path d="M12 2a15.3 15.3 0 0 1 4 10 15.3 15.3 0 0 1-4 10 15.3 15.3 0 0 1-4-10 15.3 15.3 0 0 1 4-10z"/>
</svg>
</div>
<div class="logo-text">Geo<span>Stream</span> Engine</div>
</div>
<div class="header-stats">
<div class="stat-item">
<div class="stat-value" id="totalPoints">0</div>
<div class="stat-label">Points Processed</div>
</div>
<div class="stat-item">
<div class="stat-value" id="throughput">0</div>
<div class="stat-label">Points/sec</div>
</div>
<div class="stat-item">
<div class="stat-value" id="cacheHitRate">0%</div>
<div class="stat-label">Cache Hit Rate</div>
</div>
<div class="stat-item">
<div class="stat-value" id="activeTiles">0</div>
<div class="stat-label">Active Tiles</div>
</div>
</div>
</header>
<aside class="left-panel">
<div class="panel-section">
<div class="section-title">Stream Configuration</div>
<div class="control-group">
<label class="control-label">Data Source</label>
<select class="control-select" id="dataSource">
<option value="random">Random Points</option>
<option value="clustered">Clustered Data</option>
<option value="route">Route Simulation</option>
<option value="heatmap">Heatmap Data</option>
</select>
</div>
<div class="control-group">
<label class="control-label">Stream Rate (points/sec)</label>
<div class="range-container">
<input type="range" class="range-input" id="streamRate" min="10" max="500" value="100">
<span class="range-value" id="streamRateValue">100</span>
</div>
</div>
<div class="control-group">
<label class="control-label">Buffer Size</label>
<div class="range-container">
<input type="range" class="range-input" id="bufferSize" min="100" max="5000" value="1000">
<span class="range-value" id="bufferSizeValue">1000</span>
</div>
</div>
<button class="btn btn-primary" id="startStream">Start Stream</button>
<button class="btn btn-danger" id="stopStream">Stop Stream</button>
</div>
<div class="panel-section">
<div class="section-title">Coordinate Transform</div>
<div class="control-group">
<label class="control-label">Source CRS</label>
<select class="control-select" id="sourceCRS">
<option value="WGS84">EPSG:4326 (WGS84)</option>
<option value="WebMercator">EPSG:3857 (Web Mercator)</option>
</select>
</div>
<div class="control-group">
<label class="control-label">Target CRS</label>
<select class="control-select" id="targetCRS">
<option value="WebMercator">EPSG:3857 (Web Mercator)</option>
<option value="WGS84">EPSG:4326 (WGS84)</option>
</select>
</div>
<div class="control-group">
<label class="control-label">Test Coordinates</label>
<div style="display: flex; gap: 8px;">
<input type="number" class="control-input" id="testLat" placeholder="Lat" value="40.7128" style="width: 50%">
<input type="number" class="control-input" id="testLon" placeholder="Lon" value="-74.006" style="width: 50%">
</div>
</div>
<button class="btn btn-secondary" id="transformCoords">Transform</button>
<div class="transform-preview" id="transformPreview">
<div class="transform-row">
<span class="transform-label">Input:</span>
<span class="transform-value" id="transformInput">-</span>
</div>
<div class="transform-row">
<span class="transform-label">Output:</span>
<span class="transform-value" id="transformOutput">-</span>
</div>
<div class="transform-row">
<span class="transform-label">Tile:</span>
<span class="transform-value" id="transformTile">-</span>
</div>
</div>
</div>
<div class="panel-section">
<div class="section-title">Tiling Settings</div>
<div class="control-group">
<label class="control-label">Max Zoom Level</label>
<div class="range-container">
<input type="range" class="range-input" id="maxZoom" min="1" max="18" value="12">
<span class="range-value" id="maxZoomValue">12</span>
</div>
</div>
<div class="control-group">
<label class="control-label">Tile Size (px)</label>
<select class="control-select" id="tileSize">
<option value="256">256x256</option>
<option value="512">512x512</option>
</select>
</div>
</div>
</aside>
<main class="map-container">
<canvas id="mapCanvas"></canvas>
<div class="map-overlay">
<button class="map-btn" id="zoomIn" title="Zoom In">+</button>
<button class="map-btn" id="zoomOut" title="Zoom Out">-</button>
<button class="map-btn" id="resetView" title="Reset View">⌂</button>
<button class="map-btn" id="toggleGrid" title="Toggle Grid">▦</button>
</div>
<div class="coords-display" id="coordsDisplay">
Lat: <span id="cursorLat">0.0000</span>, Lon: <span id="cursorLon">0.0000</span>
</div>
<div class="zoom-display">
Zoom: <span id="zoomLevel">1</span>
</div>
<div class="particle-container" id="particleContainer"></div>
</main>
<aside class="right-panel">
<div class="panel-section">
<div class="section-title">Cache Statistics</div>
<div class="metric-card">
<div class="metric-header">
<span class="metric-title">Cache Usage</span>
<span class="metric-value cyan" id="cacheUsage">0%</span>
</div>
<div class="metric-bar">
<div class="metric-bar-fill" id="cacheUsageBar" style="width: 0%; background: var(--accent-cyan);"></div>
</div>
</div>
<div class="metric-card">
<div class="metric-header">
<span class="metric-title">Cached Tiles</span>
<span class="metric-value green" id="cachedTiles">0</span>
</div>
</div>
</div>
<div class="panel-section">
<div class="section-title">Worker Pool</div>
<div class="worker-list" id="workerList"></div>
</div>
<div class="panel-section">
<div class="section-title">Tile Cache View</div>
<div class="tile-grid" id="tileGrid"></div>
<div class="legend">
<div class="legend-item">
<div class="legend-color" style="background: var(--accent-green);"></div>
<span>Cached</span>
</div>
<div class="legend-item">
<div class="legend-color" style="background: var(--accent-cyan);"></div>
<span>Loading</span>
</div>
<div class="legend-item">
<div class="legend-color" style="background: var(--bg-tertiary);"></div>
<span>Empty</span>
</div>
</div>
</div>
<div class="panel-section">
<div class="section-title">Stream Throughput</div>
<div class="stream-viz">
<canvas id="streamCanvas"></canvas>
</div>
</div>
<div class="panel-section">
<div class="section-title">Processing Log</div>
<div class="log-container" id="logContainer"></div>
</div>
</aside>
</div>
<script>
// ============================================
// GEOSPATIAL STREAM PROCESSING ENGINE
// ============================================
// Coordinate Transformation Engine
class CoordinateTransform {
static WGS84_TO_WEB_MERCATOR = {
a: 6378137,
maxLat: 85.0511287798,
toRadians: deg => deg * Math.PI / 180,
toDegrees: rad => rad * 180 / Math.PI
};
static wgs84ToWebMercator(lat, lon) {
const { a, maxLat, toRadians } = this.WGS84_TO_WEB_MERCATOR;
lat = Math.max(-maxLat, Math.min(maxLat, lat));
const x = a * toRadians(lon);
const y = a * Math.log(Math.tan(Math.PI / 4 + toRadians(lat) / 2));
return { x, y };
}
static webMercatorToWgs84(x, y) {
const { a, toDegrees } = this.WGS84_TO_WEB_MERCATOR;
const lon = toDegrees(x / a);
const lat = toDegrees(2 * Math.atan(Math.exp(y / a)) - Math.PI / 2);
return { lat, lon };
}
static latLonToTile(lat, lon, zoom) {
const n = Math.pow(2, zoom);
const x = Math.floor((lon + 180) / 360 * n);
const latRad = lat * Math.PI / 180;
const y = Math.floor((1 - Math.asinh(Math.tan(latRad)) / Math.PI) / 2 * n);
return { x: Math.max(0, Math.min(n - 1, x)), y: Math.max(0, Math.min(n - 1, y)), z: zoom };
}
static tileToLatLon(x, y, z) {
const n = Math.pow(2, z);
const lon = x / n * 360 - 180;
const latRad = Math.atan(Math.sinh(Math.PI * (1 - 2 * y / n)));
const lat = latRad * 180 / Math.PI;
return { lat, lon };
}
static tileBounds(x, y, z) {
const nw = this.tileToLatLon(x, y, z);
const se = this.tileToLatLon(x + 1, y + 1, z);
return { minLat: se.lat, maxLat: nw.lat, minLon: nw.lon, maxLon: se.lon };
}
}
// LRU Cache Implementation
class LRUCache {
constructor(maxSize = 1000) {
this.maxSize = maxSize;
this.cache = new Map();
this.hits = 0;
this.misses = 0;
}
get(key) {
if (this.cache.has(key)) {
const value = this.cache.get(key);
this.cache.delete(key);
this.cache.set(key, value);
this.hits++;
return value;
}
this.misses++;
return null;
}
set(key, value) {
if (this.cache.has(key)) {
this.cache.delete(key);
} else if (this.cache.size >= this.maxSize) {
const firstKey = this.cache.keys().next().value;
this.cache.delete(firstKey);
}
this.cache.set(key, value);
}
has(key) {
return this.cache.has(key);
}
clear() {
this.cache.clear();
this.hits = 0;
this.misses = 0;
}
getHitRate() {
const total = this.hits + this.misses;
return total > 0 ? (this.hits / total * 100).toFixed(1) : 0;
}
size() {
return this.cache.size;
}
}
// Dynamic Tiling System
class TileManager {
constructor(maxZoom = 12, tileSize = 256) {
this.maxZoom = maxZoom;
this.tileSize = tileSize;
this.cache = new LRUCache(500);
this.pendingTiles = new Set();
}
getTileKey(x, y, z) {
return `${z}/${x}/${y}`;
}
getTile(lat, lon, zoom) {
const tile = CoordinateTransform.latLonToTile(lat, lon, zoom);
const key = this.getTileKey(tile.x, tile.y, tile.z);
let tileData = this.cache.get(key);
if (!tileData) {
tileData = this.createTile(tile.x, tile.y, tile.z);
this.cache.set(key, tileData);
}
return { ...tile, data: tileData, key };
}
createTile(x, y, z) {
const bounds = CoordinateTransform.tileBounds(x, y, z);
return {
x, y, z,
bounds,
points: [],
features: [],
lastAccess: Date.now(),
loadCount: 0
};
}
addPointToTile(lat, lon, properties = {}) {
for (let z = 1; z <= this.maxZoom; z++) {
const tile = this.getTile(lat, lon, z);
const key = tile.key;
let tileData = this.cache.get(key);
if (!tileData) {
tileData = this.createTile(tile.x, tile.y, tile.z);
this.cache.set(key, tileData);
}
tileData.points.push({ lat, lon, properties, timestamp: Date.now() });
tileData.lastAccess = Date.now();
}
}
getVisibleTiles(viewBounds, zoom) {
const tiles = [];
const z = Math.min(Math.floor(zoom), this.maxZoom);
const nw = CoordinateTransform.latLonToTile(viewBounds.maxLat, viewBounds.minLon, z);
const se = CoordinateTransform.latLonToTile(viewBounds.minLat, viewBounds.maxLon, z);
for (let x = nw.x; x <= se.x; x++) {
for (let y = nw.y; y <= se.y; y++) {
const key = this.getTileKey(x, y, z);
let tileData = this.cache.get(key);
if (!tileData) {
tileData = this.createTile(x, y, z);
this.cache.set(key, tileData);
}
tiles.push({ x, y, z, data: tileData, key });
}
}
return tiles;
}
getCacheStats() {
return {
size: this.cache.size(),
hitRate: this.cache.getHitRate(),
hits: this.cache.hits,
misses: this.cache.misses
};
}
}
// Load Balancer with Work Stealing
class LoadBalancer {
constructor(numWorkers = 4) {
this.workers = [];
this.taskQueue = [];
this.completedTasks = 0;
for (let i = 0; i < numWorkers; i++) {
this.workers.push({
id: i,
load: 0,
tasks: [],
status: 'idle',
totalProcessed: 0
});
}
}
addTask(task) {
const worker = this.getLeastLoadedWorker();
worker.tasks.push(task);
worker.load = worker.tasks.length;
this.updateWorkerStatus(worker);
return worker.id;
}
getLeastLoadedWorker() {
return this.workers.reduce((min, w) => w.load < min.load ? w : min, this.workers[0]);
}
updateWorkerStatus(worker) {
if (worker.load === 0) {
worker.status = 'idle';
} else if (worker.load < 5) {
worker.status = 'active';
} else {
worker.status = 'busy';
}
}
processTasks() {
this.workers.forEach(worker => {
if (worker.tasks.length > 0) {
const task = worker.tasks.shift();
worker.load = worker.tasks.length;
worker.totalProcessed++;
this.completedTasks++;
this.updateWorkerStatus(worker);
return task;
}
});
}
stealWork() {
const busyWorkers = this.workers.filter(w => w.load > 3);
const idleWorkers = this.workers.filter(w => w.load === 0);
if (busyWorkers.length > 0 && idleWorkers.length > 0) {
const busy = busyWorkers[0];
const idle = idleWorkers[0];
const stolen = busy.tasks.splice(0, Math.floor(busy.tasks.length / 2));
idle.tasks = stolen;
busy.load = busy.tasks.length;
idle.load = idle.tasks.length;
this.updateWorkerStatus(busy);
this.updateWorkerStatus(idle);
}
}
getStats() {
return {
totalTasks: this.completedTasks,
avgLoad: this.workers.reduce((sum, w) => sum + w.load, 0) / this.workers.length,
workers: this.workers.map(w => ({
id: w.id,
load: w.load,
status: w.status,
processed: w.totalProcessed
}))
};
}
}
// Stream Processor
class StreamProcessor {
constructor(tileManager, loadBalancer) {
this.tileManager = tileManager;
this.loadBalancer = loadBalancer;
this.buffer = [];
this.bufferSize = 1000;
this.isRunning = false;
this.streamRate = 100;
this.totalPoints = 0;
this.throughputHistory = [];
this.dataSource = 'random';
this.lastClusterCenter = { lat: 40, lon: -74 };
this.routeProgress = 0;
}
setDataSource(type) {
this.dataSource = type;
}
generatePoint() {
switch (this.dataSource) {
case 'random':
return {
lat: (Math.random() - 0.5) * 140,
lon: (Math.random() - 0.5) * 340,
properties: { type: 'random', value: Math.random() }
};
case 'clustered':
const clusterOffset = {
lat: (Math.random() - 0.5) * 10,
lon: (Math.random() - 0.5) * 10
};
if (Math.random() < 0.05) {
this.lastClusterCenter = {
lat: (Math.random() - 0.5) * 120,
lon: (Math.random() - 0.5) * 300
};
}
return {
lat: this.lastClusterCenter.lat + clusterOffset.lat,
lon: this.lastClusterCenter.lon + clusterOffset.lon,
properties: { type: 'clustered', value: Math.random() }
};
case 'route':
this.routeProgress += 0.01;
return {
lat: 40 + Math.sin(this.routeProgress) * 20,
lon: -74 + this.routeProgress * 5 % 180,
properties: { type: 'route', value: this.routeProgress }
};
case 'heatmap':
const centerX = Math.random() * 2 - 1;
const centerY = Math.random() * 2 - 1;
return {
lat: 35 + centerX * centerX * Math.sign(centerX) * 15,
lon: -100 + centerY * centerY * Math.sign(centerY) * 50,
properties: { type: 'heatmap', intensity: Math.random() }
};
default:
return this.generatePoint();
}
}
ingestPoint(point) {
this.buffer.push(point);
if (this.buffer.length >= this.bufferSize) {
this.flush();
}
}
flush() {
const points = this.buffer.splice(0, this.buffer.length);
points.forEach(point => {
this.tileManager.addPointToTile(point.lat, point.lon, point.properties);
this.loadBalancer.addTask({ type: 'point', data: point });
this.totalPoints++;
});
}
start() {
if (this.isRunning) return;
this.isRunning = true;
this.processLoop();
}
stop() {
this.isRunning = false;
this.flush();
}
processLoop() {
if (!this.isRunning) return;
const pointsPerFrame = Math.ceil(this.streamRate / 60);
for (let i = 0; i < pointsPerFrame; i++) {
const point = this.generatePoint();
this.ingestPoint(point);
}
this.loadBalancer.processTasks();
if (Math.random() < 0.1) {
this.loadBalancer.stealWork();
}
requestAnimationFrame(() => this.processLoop());
}
getThroughput() {
return this.streamRate;
}
}
// Map Renderer
class MapRenderer {
constructor(canvas, tileManager) {
this.canvas = canvas;
this.ctx = canvas.getContext('2d');
this.tileManager = tileManager;
this.center = { lat: 20, lon: 0 };
this.zoom = 2;
this.showGrid = true;
this.pointDecay = 5000;
this.isDragging = false;
this.lastMouse = { x: 0, y: 0 };
this.setupCanvas();
this.setupEvents();
}
setupCanvas() {
const rect = this.canvas.parentElement.getBoundingClientRect();
this.canvas.width = rect.width * window.devicePixelRatio;
this.canvas.height = rect.height * window.devicePixelRatio;
this.canvas.style.width = rect.width + 'px';
this.canvas.style.height = rect.height + 'px';
this.ctx.scale(window.devicePixelRatio, window.devicePixelRatio);
this.width = rect.width;
this.height = rect.height;
}
setupEvents() {
this.canvas.addEventListener('mousedown', (e) => {
this.isDragging = true;
this.lastMouse = { x: e.clientX, y: e.clientY };
});
this.canvas.addEventListener('mousemove', (e) => {
const rect = this.canvas.getBoundingClientRect();
const x = e.clientX - rect.left;
const y = e.clientY - rect.top;
const coords = this.screenToCoords(x, y);
document.getElementById('cursorLat').textContent = coords.lat.toFixed(4);
document.getElementById('cursorLon').textContent = coords.lon.toFixed(4);
if (this.isDragging) {
const dx = e.clientX - this.lastMouse.x;
const dy = e.clientY - this.lastMouse.y;
const scale = this.getScale();
this.center.lon -= dx / scale;
this.center.lat += dy / scale * 0.8;
this.lastMouse = { x: e.clientX, y: e.clientY };
}
});
this.canvas.addEventListener('mouseup', () => {
this.isDragging = false;
});
this.canvas.addEventListener('mouseleave', () => {
this.isDragging = false;
});
this.canvas.addEventListener('wheel', (e) => {
e.preventDefault();
const delta = e.deltaY > 0 ? -0.5 : 0.5;
this.zoom = Math.max(1, Math.min(18, this.zoom + delta));
document.getElementById('zoomLevel').textContent = this.zoom.toFixed(1);
});
}
getScale() {
return Math.pow(2, this.zoom) * 50;
}
coordsToScreen(lat, lon) {
const scale = this.getScale();
const x = this.width / 2 + (lon - this.center.lon) * scale;
const y = this.height / 2 - (lat - this.center.lat) * scale * 0.8;
return { x, y };
}
screenToCoords(x, y) {
const scale = this.getScale();
const lon = this.center.lon + (x - this.width / 2) / scale;
const lat = this.center.lat - (y - this.height / 2) / scale * 1.25;
return { lat, lon };
}
getViewBounds() {
const nw = this.screenToCoords(0, 0);
const se = this.screenToCoords(this.width, this.height);
return {
minLat: Math.min(nw.lat, se.lat),
maxLat: Math.max(nw.lat, se.lat),
minLon: Math.min(nw.lon, se.lon),
maxLon: Math.max(nw.lon, se.lon)
};
}
render() {
const ctx = this.ctx;
// Background
const gradient = ctx.createLinearGradient(0, 0, 0, this.height);
gradient.addColorStop(0, '#0a1628');
gradient.addColorStop(1, '#0d1f3c');
ctx.fillStyle = gradient;
ctx.fillRect(0, 0, this.width, this.height);
// Grid
if (this.showGrid) {
this.renderGrid();
}
// Tiles
const bounds = this.getViewBounds();
const tiles = this.tileManager.getVisibleTiles(bounds, Math.floor(this.zoom));
this.renderTiles(tiles);
// Points
this.renderPoints(tiles);
return tiles.length;
}
renderGrid() {
const ctx = this.ctx;
const bounds = this.getViewBounds();
ctx.strokeStyle = 'rgba(0, 212, 255, 0.1)';
ctx.lineWidth = 1;
// Longitude lines
const lonStep = Math.pow(10, Math.floor(2 - Math.log10(this.zoom + 1)));
for (let lon = Math.floor(bounds.minLon / lonStep) * lonStep; lon <= bounds.maxLon; lon += lonStep) {
const start = this.coordsToScreen(90, lon);
const end = this.coordsToScreen(-90, lon);
ctx.beginPath();
ctx.moveTo(start.x, 0);
ctx.lineTo(end.x, this.height);
ctx.stroke();
}
// Latitude lines
const latStep = lonStep;
for (let lat = Math.floor(bounds.minLat / latStep) * latStep; lat <= bounds.maxLat; lat += latStep) {
const start = this.coordsToScreen(lat, -180);
const end = this.coordsToScreen(lat, 180);
ctx.beginPath();
ctx.moveTo(0, start.y);
ctx.lineTo(this.width, end.y);
ctx.stroke();
}
}
renderTiles(tiles) {
const ctx = this.ctx;
tiles.forEach(tile => {
const bounds = tile.data.bounds;
const nw = this.coordsToScreen(bounds.maxLat, bounds.minLon);
const se = this.coordsToScreen(bounds.minLat, bounds.maxLon);
const width = se.x - nw.x;
const height = se.y - nw.y;
if (width < 2 || height < 2) return;
// Tile background
ctx.fillStyle = 'rgba(0, 212, 255, 0.03)';
ctx.fillRect(nw.x, nw.y, width, height);
// Tile border
ctx.strokeStyle = 'rgba(0, 212, 255, 0.2)';
ctx.lineWidth = 1;
ctx.strokeRect(nw.x, nw.y, width, height);
// Tile label
if (width > 40 && height > 30) {
ctx.fillStyle = 'rgba(0, 212, 255, 0.4)';
ctx.font = '10px Consolas';
ctx.fillText(`${tile.z}/${tile.x}/${tile.y}`, nw.x + 4, nw.y + 12);
ctx.fillText(`${tile.data.points.length} pts`, nw.x + 4, nw.y + 24);
}
});
}
renderPoints(tiles) {
const ctx = this.ctx;
const now = Date.now();
const colorMap = {
'random': '#00d4ff',
'clustered': '#10b981',
'route': '#ff6b35',
'heatmap': '#fbbf24'
};
tiles.forEach(tile => {
const points = tile.data.points;
const recentPoints = points.filter(p => now - p.timestamp < this.pointDecay);
recentPoints.forEach(point => {
const pos = this.coordsToScreen(point.lat, point.lon);
if (pos.x < -10 || pos.x > this.width + 10 || pos.y < -10 || pos.y > this.height + 10) return;
const age = now - point.timestamp;
const alpha = Math.max(0.1, 1 - age / this.pointDecay);
const color = colorMap[point.properties.type] || '#00d4ff';
// Glow effect
const radius = 3 + (1 - alpha) * 2;
const grd = ctx.createRadialGradient(pos.x, pos.y, 0, pos.x, pos.y, radius * 3);
grd.addColorStop(0, color);
grd.addColorStop(1, 'transparent');
ctx.globalAlpha = alpha * 0.3;
ctx.fillStyle = grd;
ctx.beginPath();
ctx.arc(pos.x, pos.y, radius * 3, 0, Math.PI * 2);
ctx.fill();
// Core point
ctx.globalAlpha = alpha;
ctx.fillStyle = color;
ctx.beginPath();
ctx.arc(pos.x, pos.y, radius, 0, Math.PI * 2);
ctx.fill();
});
});
ctx.globalAlpha = 1;
}
}
// Stream Visualization
class StreamVisualizer {
constructor(canvas) {
this.canvas = canvas;
this.ctx = canvas.getContext('2d');
this.data = [];
this.maxPoints = 100;
const rect = canvas.parentElement.getBoundingClientRect();
this.canvas.width = rect.width * window.devicePixelRatio;
this.canvas.height = rect.height * window.devicePixelRatio;
this.canvas.style.width = rect.width + 'px';
this.canvas.style.height = rect.height + 'px';
this.ctx.scale(window.devicePixelRatio, window.devicePixelRatio);
this.width = rect.width;
this.height = rect.height;
}
addDataPoint(value) {
this.data.push(value);
if (this.data.length > this.maxPoints) {
this.data.shift();
}
}
render() {
const ctx = this.ctx;
ctx.fillStyle = '#1e293b';
ctx.fillRect(0, 0, this.width, this.height);
if (this.data.length < 2) return;
const max = Math.max(...this.data, 100);
const step = this.width / this.maxPoints;
// Area fill
ctx.beginPath();
ctx.moveTo(0, this.height);
this.data.forEach((val, i) => {
const x = i * step;
const y = this.height - (val / max) * (this.height - 10);
if (i === 0) ctx.lineTo(x, y);
else ctx.lineTo(x, y);
});
ctx.lineTo((this.data.length - 1) * step, this.height);
ctx.closePath();
const gradient = ctx.createLinearGradient(0, 0, 0, this.height);
gradient.addColorStop(0, 'rgba(0, 212, 255, 0.3)');
gradient.addColorStop(1, 'rgba(0, 212, 255, 0)');
ctx.fillStyle = gradient;
ctx.fill();
// Line
ctx.beginPath();
this.data.forEach((val, i) => {
const x = i * step;
const y = this.height - (val / max) * (this.height - 10);
if (i === 0) ctx.moveTo(x, y);
else ctx.lineTo(x, y);
});
ctx.strokeStyle = '#00d4ff';
ctx.lineWidth = 2;
ctx.stroke();
}
}
// Main Application
class GeoStreamEngine {
constructor() {
this.tileManager = new TileManager(12, 256);
this.loadBalancer = new LoadBalancer(4);
this.streamProcessor = new StreamProcessor(this.tileManager, this.loadBalancer);
this.mapCanvas = document.getElementById('mapCanvas');
this.mapRenderer = new MapRenderer(this.mapCanvas, this.tileManager);
this.streamCanvas = document.getElementById('streamCanvas');
this.streamVisualizer = new StreamVisualizer(this.streamCanvas);
this.frameCount = 0;
this.lastTime = performance.now();
this.setupUI();
this.startMainLoop();
}
setupUI() {
// Stream controls
document.getElementById('startStream').addEventListener('click', () => {
this.streamProcessor.start();
this.log('Stream started', 'success');
});
document.getElementById('stopStream').addEventListener('click', () => {
this.streamProcessor.stop();
this.log('Stream stopped', 'warn');
});
document.getElementById('streamRate').addEventListener('input', (e) => {
this.streamProcessor.streamRate = parseInt(e.target.value);
document.getElementById('streamRateValue').textContent = e.target.value;
});
document.getElementById('bufferSize').addEventListener('input', (e) => {
this.streamProcessor.bufferSize = parseInt(e.target.value);
document.getElementById('bufferSizeValue').textContent = e.target.value;
});
document.getElementById('dataSource').addEventListener('change', (e) => {
this.streamProcessor.setDataSource(e.target.value);
this.log(`Data source: ${e.target.value}`, 'info');
});
// Map controls
document.getElementById('zoomIn').addEventListener('click', () => {
this.mapRenderer.zoom = Math.min(18, this.mapRenderer.zoom + 1);
document.getElementById('zoomLevel').textContent = this.mapRenderer.zoom.toFixed(1);
});
document.getElementById('zoomOut').addEventListener('click', () => {
this.mapRenderer.zoom = Math.max(1, this.mapRenderer.zoom - 1);
document.getElementById('zoomLevel').textContent = this.mapRenderer.zoom.toFixed(1);
});
document.getElementById('resetView').addEventListener('click', () => {
this.mapRenderer.center = { lat: 20, lon: 0 };
this.mapRenderer.zoom = 2;
document.getElementById('zoomLevel').textContent = '2';
});
document.getElementById('toggleGrid').addEventListener('click', () => {
this.mapRenderer.showGrid = !this.mapRenderer.showGrid;
});
// Tiling controls
document.getElementById('maxZoom').addEventListener('input', (e) => {
this.tileManager.maxZoom = parseInt(e.target.value);
document.getElementById('maxZoomValue').textContent = e.target.value;
});
// Transform controls
document.getElementById('transformCoords').addEventListener('click', () => {
const lat = parseFloat(document.getElementById('testLat').value);
const lon = parseFloat(document.getElementById('testLon').value);
const sourceCRS = document.getElementById('sourceCRS').value;
const targetCRS = document.getElementById('targetCRS').value;
let result;
if (sourceCRS === 'WGS84' && targetCRS === 'WebMercator') {
result = CoordinateTransform.wgs84ToWebMercator(lat, lon);
document.getElementById('transformInput').textContent = `${lat.toFixed(6)}, ${lon.toFixed(6)}`;
document.getElementById('transformOutput').textContent = `X: ${result.x.toFixed(2)}, Y: ${result.y.toFixed(2)}`;
} else if (sourceCRS === 'WebMercator' && targetCRS === 'WGS84') {
result = CoordinateTransform.webMercatorToWgs84(lat, lon);
document.getElementById('transformInput').textContent = `X: ${lat.toFixed(2)}, Y: ${lon.toFixed(2)}`;
document.getElementById('transformOutput').textContent = `${result.lat.toFixed(6)}, ${result.lon.toFixed(6)}`;
} else {
result = { lat, lon };
document.getElementById('transformInput').textContent = `${lat.toFixed(6)}, ${lon.toFixed(6)}`;
document.getElementById('transformOutput').textContent = `${lat.toFixed(6)}, ${lon.toFixed(6)}`;
}
const tile = CoordinateTransform.latLonToTile(
sourceCRS === 'WGS84' ? lat : result.lat,
sourceCRS === 'WGS84' ? lon : result.lon,
10
);
document.getElementById('transformTile').textContent = `${tile.z}/${tile.x}/${tile.y}`;
this.log(`Transform: ${sourceCRS} → ${targetCRS}`, 'info');
});
// Initialize tile grid
this.updateTileGrid();
}
log(message, type = 'info') {
const container = document.getElementById('logContainer');
const time = new Date().toLocaleTimeString();
const entry = document.createElement('div');
entry.className = `log-entry ${type}`;
entry.innerHTML = `<span class="log-time">${time}</span>${message}`;
container.insertBefore(entry, container.firstChild);
if (container.children.length > 50) {
container.removeChild(container.lastChild);
}
}
updateStats() {
const stats = this.tileManager.getCacheStats();
const lbStats = this.loadBalancer.getStats();
document.getElementById('totalPoints').textContent = this.streamProcessor.totalPoints.toLocaleString();
document.getElementById('throughput').textContent = this.streamProcessor.getThroughput();
document.getElementById('cacheHitRate').textContent = stats.hitRate + '%';
document.getElementById('cacheUsage').textContent = ((stats.size / 500) * 100).toFixed(0) + '%';
document.getElementById('cacheUsageBar').style.width = ((stats.size / 500) * 100) + '%';
document.getElementById('cachedTiles').textContent = stats.size;
// Update worker list
const workerList = document.getElementById('workerList');
workerList.innerHTML = lbStats.workers.map(w => `
<div class="worker-item">
<div class="worker-status ${w.status}"></div>
<div class="worker-info">
<div class="worker-name">Worker ${w.id + 1}</div>
<div class="worker-load">Load: ${w.load} | Processed: ${w.processed}</div>
</div>
</div>
`).join('');
// Update throughput visualization
this.streamVisualizer.addDataPoint(this.streamProcessor.getThroughput());
this.streamVisualizer.render();
}
updateTileGrid() {
const grid = document.getElementById('tileGrid');
const zoom = Math.floor(this.mapRenderer.zoom);
const n = Math.min(4, Math.pow(2, zoom));
grid.innerHTML = '';
for (let y = 0; y < 4; y++) {
for (let x = 0; x < 4; x++) {
const key = this.tileManager.getTileKey(x, y, zoom);
const isCached = this.tileManager.cache.has(key);
const isLoading = this.tileManager.pendingTiles.has(key);
const cell = document.createElement('div');
cell.className = `tile-cell ${isCached ? 'cached' : ''} ${isLoading ? 'loading' : ''}`;
cell.textContent = `${x},${y}`;
grid.appendChild(cell);
}
}
}
startMainLoop() {
const loop = () => {
this.frameCount++;
// Render map
const activeTiles = this.mapRenderer.render();
document.getElementById('activeTiles').textContent = activeTiles;
// Update stats every 10 frames
if (this.frameCount % 10 === 0) {
this.updateStats();
this.updateTileGrid();
}
requestAnimationFrame(loop);
};
loop();
}
}
// Initialize application
window.addEventListener('load', () => {
window.app = new GeoStreamEngine();
// Handle resize
window.addEventListener('resize', () => {
app.mapRenderer.setupCanvas();
app.streamVisualizer = new StreamVisualizer(app.streamCanvas);
});
});
</script>
</body>
</html>