Spaces:
Running
Running
File size: 19,525 Bytes
cf9f0b3 d92538c cf9f0b3 7ff8148 210573a d92538c cf9f0b3 d92538c 210573a d92538c 210573a d92538c 210573a cf9f0b3 d92538c cf9f0b3 d92538c cf9f0b3 7ff8148 cf9f0b3 b21f67e cf9f0b3 b21f67e cf9f0b3 b21f67e cf9f0b3 b21f67e cf9f0b3 b21f67e cf9f0b3 b21f67e cf9f0b3 7ff8148 cf9f0b3 d92538c b21f67e cf9f0b3 d92538c b21f67e cf9f0b3 b21f67e cf9f0b3 d92538c cf9f0b3 7ff8148 cf9f0b3 7ff8148 cf9f0b3 d92538c cf9f0b3 d92538c cf9f0b3 d92538c cf9f0b3 | 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 125 126 127 128 129 130 131 132 133 134 135 136 137 138 139 140 141 142 143 144 145 146 147 148 149 150 151 152 153 154 155 156 157 158 159 160 161 162 163 164 165 166 167 168 169 170 171 172 173 174 175 176 177 178 179 180 181 182 183 184 185 186 187 188 189 190 191 192 193 194 195 196 197 198 199 200 201 202 203 204 205 206 207 208 209 210 211 212 213 214 215 216 217 218 219 220 221 222 223 224 225 226 227 228 229 230 231 232 233 234 235 236 237 238 239 240 241 242 243 244 245 246 247 248 249 250 251 252 253 254 255 256 257 258 259 260 261 262 263 264 265 266 267 268 269 270 271 272 273 274 275 276 277 278 279 280 281 282 283 284 285 286 287 288 289 290 291 292 293 294 295 296 297 298 299 300 301 302 303 304 305 306 307 308 309 310 311 312 313 314 315 316 317 318 319 320 321 322 323 324 325 326 327 328 329 330 331 332 333 334 335 336 337 338 339 340 341 342 343 344 345 346 347 348 349 350 351 352 353 354 355 356 357 358 359 360 361 362 363 364 365 366 367 368 369 370 371 372 373 374 375 376 377 378 379 380 381 382 383 384 385 386 387 388 389 390 391 392 393 394 395 396 397 398 399 400 401 402 403 404 405 406 407 408 409 410 411 412 413 414 415 416 417 418 419 420 421 422 423 424 425 426 427 428 429 430 431 432 433 434 435 436 437 438 439 440 441 442 443 444 445 446 447 448 449 450 451 452 453 454 455 456 457 458 459 460 461 462 463 464 465 466 467 468 469 470 471 472 473 474 475 476 477 478 479 480 481 482 483 484 485 486 487 488 489 490 491 492 493 494 495 496 497 498 499 500 501 |
// Main JavaScript for MapVoyage Compass
// API Configuration
const API_BASE_URL = 'https://ocpp.neto.mx:8082/api';
const ACCESS_TOKEN = '1bc2b30bcde5c4a31a1e6d6e8637e149f16102f43c46db22ca19ddd1348cb745';
// Global variables
let map;
let chargePointMarkers = [];
let chargePointLayerGroup;
let refreshInterval;
// Initialize OpenStreetMap with Positron style
function initMap() {
// Default coordinates (centered on Mexico)
const defaultLat = 23.6345;
const defaultLng = -102.5528;
const defaultZoom = 5;
// Create map instance with zoom control disabled
map = L.map('map', {
zoomControl: false
}).setView([defaultLat, defaultLng], defaultZoom);
// Add Positron tile layer (CartoDB Positron)
L.tileLayer('https://{s}.basemaps.cartocdn.com/light_all/{z}/{x}/{y}{r}.png', {
attribution: '© <a href="https://www.openstreetmap.org/copyright">OpenStreetMap</a> contributors © <a href="https://carto.com/attributions">CARTO</a>',
subdomains: 'abcd',
maxZoom: 19,
}).addTo(map);
// Create a layer group for charge points
chargePointLayerGroup = L.layerGroup().addTo(map);
// Add a marker at the center
const marker = L.marker([defaultLat, defaultLng]).addTo(map);
marker.bindPopup('<b>Welcome to MapVoyage Compass! 🧭</b><br>Now showing electric vehicle charge points.').openPopup();
// Add click event to get coordinates
map.on('click', function(e) {
const popup = L.popup()
.setLatLng(e.latlng)
.setContent(`You clicked at: <br>${e.latlng.lat.toFixed(4)}, ${e.latlng.lng.toFixed(4)}`)
.openOn(map);
});
// Load charge points from API
loadChargePoints();
// Start auto‑refresh every 10 seconds
startAutoRefresh();
// Store map instance globally for other functions
window.map = map;
}
// Load charge points from API
async function loadChargePoints() {
try {
// Silent load: no notification
const response = await fetch(`${API_BASE_URL}/charge_points`, {
method: 'GET',
headers: {
'Authorization': `Bearer ${ACCESS_TOKEN}`,
'Content-Type': 'application/json'
}
});
if (!response.ok) {
throw new Error(`API error: ${response.status}`);
}
const chargePoints = await response.json();
// Filter points with valid coordinates
const validPoints = chargePoints.filter(point =>
point.latitude && point.longitude &&
point.latitude !== 'null' && point.longitude !== 'null' &&
!isNaN(parseFloat(point.latitude)) && !isNaN(parseFloat(point.longitude))
);
if (validPoints.length === 0) {
// No valid points, but do nothing silently
return;
}
// Create a lookup of existing markers by IDs (or coordinates) to update/remove
// For simplicity, we'll clear and re‑add, but keep the map view.
// First, store current map view to preserve it.
const currentCenter = map.getCenter();
const currentZoom = map.getZoom();
// Clear existing markers
chargePointMarkers.forEach(marker => marker.remove());
chargePointMarkers = [];
chargePointLayerGroup.clearLayers();
// Create markers for each charge point
validPoints.forEach(point => {
const marker = createChargePointMarker(point);
chargePointMarkers.push(marker);
chargePointLayerGroup.addLayer(marker);
});
// Restore map view (no recentering)
map.setView(currentCenter, currentZoom);
// No success notification
} catch (error) {
console.error('Error loading charge points:', error);
// Silent fallback to demo data
loadDemoChargePoints();
}
}
// Start auto‑refresh every 10 seconds
function startAutoRefresh() {
if (refreshInterval) {
clearInterval(refreshInterval);
}
refreshInterval = setInterval(() => {
loadChargePoints();
console.log('Auto‑refresh executed at', new Date().toLocaleTimeString());
}, 10000); // 10 seconds
}
// Stop auto‑refresh (useful for manual control)
function stopAutoRefresh() {
if (refreshInterval) {
clearInterval(refreshInterval);
refreshInterval = null;
showNotification('Auto‑refresh stopped');
}
}
// Toggle auto‑refresh on/off
function toggleAutoRefresh() {
if (refreshInterval) {
stopAutoRefresh();
} else {
startAutoRefresh();
}
}
// Create a marker for a charge point
function createChargePointMarker(chargePoint) {
// Determine color based on status
let color = '#3b82f6'; // Default blue
let fillColor = '#8b5cf6';
if (chargePoint.last_heartbeat) {
const lastHeartbeat = new Date(chargePoint.last_heartbeat);
const now = new Date();
const hoursDiff = (now - lastHeartbeat) / (1000 * 60 * 60);
if (hoursDiff > 24) {
color = '#ef4444'; // Red for offline (>24h)
fillColor = '#f87171';
} else if (hoursDiff > 1) {
color = '#f59e0b'; // Yellow for stale (1-24h)
fillColor = '#fbbf24';
} else {
color = '#10b981'; // Green for recent (<1h)
fillColor = '#34d399';
}
}
// Create custom icon
const icon = L.divIcon({
html: `
<div style="
background: ${color};
width: 24px;
height: 24px;
border-radius: 50%;
border: 3px solid white;
box-shadow: 0 2px 4px rgba(0,0,0,0.3);
display: flex;
align-items: center;
justify-content: center;
color: white;
font-weight: bold;
font-size: 12px;
">
<i data-feather="battery-charging" style="width: 12px; height: 12px;"></i>
</div>
`,
className: 'charge-point-marker',
iconSize: [24, 24],
iconAnchor: [12, 12]
});
const lat = parseFloat(chargePoint.latitude);
const lng = parseFloat(chargePoint.longitude);
const marker = L.marker([lat, lng], { icon: icon });
// Create popup content
const popupContent = `
<div style="min-width: 250px; font-family: system-ui, -apple-system, sans-serif;">
<div style="display: flex; align-items: center; margin-bottom: 10px;">
<div style="width: 40px; height: 40px; background: ${color}; border-radius: 8px; display: flex; align-items: center; justify-content: center; margin-right: 10px;">
<i data-feather="battery-charging" style="width: 20px; height: 20px; color: white;"></i>
</div>
<div>
<h3 style="margin: 0; font-weight: 600; color: #1f2937;">Charge Point #${chargePoint.id}</h3>
<p style="margin: 2px 0 0 0; font-size: 12px; color: #6b7280;">${chargePoint.vendor || 'Unknown Vendor'}</p>
</div>
</div>
<div style="background: #f9fafb; border-radius: 8px; padding: 12px; margin-bottom: 10px;">
<div style="display: flex; justify-content: space-between; margin-bottom: 6px;">
<span style="font-size: 13px; color: #6b7280;">Model:</span>
<span style="font-weight: 500; color: #374151;">${chargePoint.model || 'N/A'}</span>
</div>
<div style="display: flex; justify-content: space-between; margin-bottom: 6px;">
<span style="font-size: 13px; color: #6b7280;">Connectors:</span>
<span style="font-weight: 500; color: #374151;">${chargePoint.num_connectors || 'N/A'}</span>
</div>
<div style="display: flex; justify-content: space-between; margin-bottom: 6px;">
<span style="font-size: 13px; color: #6b7280;">Serial:</span>
<span style="font-weight: 500; color: #374151;">${chargePoint.serial_number || 'N/A'}</span>
</div>
<div style="display: flex; justify-content: space-between;">
<span style="font-size: 13px; color: #6b7280;">Last Heartbeat:</span>
<span style="font-weight: 500; color: #374151;">${chargePoint.last_heartbeat ? new Date(chargePoint.last_heartbeat).toLocaleString() : 'Never'}</span>
</div>
</div>
${chargePoint.address ? `
<div style="margin-top: 8px; padding-top: 8px; border-top: 1px solid #e5e7eb;">
<p style="margin: 0; font-size: 13px; color: #6b7280;">Address:</p>
<p style="margin: 4px 0 0 0; font-size: 14px; color: #374151;">${chargePoint.address}</p>
</div>
` : ''}
<div style="margin-top: 12px; display: flex; justify-content: space-between;">
<button onclick="navigateToPoint(${lat}, ${lng})" style="
background: #3b82f6;
color: white;
border: none;
border-radius: 6px;
padding: 6px 12px;
font-size: 12px;
cursor: pointer;
display: flex;
align-items: center;
gap: 4px;
">
<i data-feather="navigation" style="width: 12px; height: 12px;"></i>
Navigate
</button>
<button onclick="showDetails(${chargePoint.id})" style="
background: #f3f4f6;
color: #374151;
border: 1px solid #d1d5db;
border-radius: 6px;
padding: 6px 12px;
font-size: 12px;
cursor: pointer;
display: flex;
align-items: center;
gap: 4px;
">
<i data-feather="info" style="width: 12px; height: 12px;"></i>
Details
</button>
</div>
</div>
`;
marker.bindPopup(popupContent);
// Initialize feather icons in popup when it opens
marker.on('popupopen', () => {
feather.replace();
});
return marker;
}
// Load demo charge points if API fails
function loadDemoChargePoints() {
const demoPoints = [
{
id: 1,
address: "Sta. Barbara 1993, Jardines de la Silla, 67287 Jardines de la Silla, N.L.",
latitude: "25.632163",
longitude: "-100.178570",
model: "AC-Pro",
vendor: "DELTRIX",
num_connectors: 1,
serial_number: "gbt001",
last_heartbeat: "2025-12-28 07:41:21"
},
{
id: 2,
address: "Sta. Barbara 1993, Jardines de la Silla, 67287 Jardines de la Silla, N.L.",
latitude: "25.631998",
longitude: "-100.179111",
model: "CCS2+GBT",
vendor: "",
num_connectors: 2,
serial_number: "1993",
last_heartbeat: "2025-12-28 07:41:21"
},
{
id: 3,
address: "Santa Barbara 1983, Jardines de la Silla, Juarez, N.L.",
latitude: "25.632263",
longitude: "-100.178152",
model: "",
vendor: "charger Point",
num_connectors: 1,
serial_number: "1985",
last_heartbeat: "2025-12-28 07:41:22"
}
];
// Store current view to preserve it
const currentCenter = map.getCenter();
const currentZoom = map.getZoom();
demoPoints.forEach(point => {
const marker = createChargePointMarker(point);
chargePointMarkers.push(marker);
chargePointLayerGroup.addLayer(marker);
});
// Keep the same map view (no recentering)
map.setView(currentCenter, currentZoom);
}
// Navigate to a point (center map on it)
function navigateToPoint(lat, lng) {
map.setView([lat, lng], 15);
// Open popup if marker exists
chargePointMarkers.forEach(marker => {
const markerLatLng = marker.getLatLng();
if (markerLatLng.lat === lat && markerLatLng.lng === lng) {
marker.openPopup();
}
});
showNotification(`Navigating to charge point at ${lat.toFixed(4)}, ${lng.toFixed(4)}`);
}
// Show details for a charge point
function showDetails(pointId) {
// In a real app, this would fetch more details from the API
showNotification(`Loading details for charge point #${pointId}...`);
// Simulate API call
setTimeout(() => {
const modal = document.createElement('div');
modal.className = 'fixed inset-0 z-50 flex items-center justify-center p-4';
modal.style.backgroundColor = 'rgba(0, 0, 0, 0.5)';
modal.innerHTML = `
<div class="bg-white rounded-2xl shadow-2xl max-w-md w-full p-6">
<div class="flex justify-between items-center mb-4">
<h3 class="text-xl font-bold text-gray-800">Charge Point #${pointId} Details</h3>
<button id="closeModal" class="text-gray-400 hover:text-gray-600">
<i data-feather="x" class="w-6 h-6"></i>
</button>
</div>
<div class="space-y-4">
<div class="bg-blue-50 p-4 rounded-xl">
<div class="flex items-center">
<i data-feather="info" class="w-5 h-5 text-blue-600 mr-2"></i>
<p class="text-blue-800">Detailed information would be fetched from the API for point ID ${pointId}.</p>
</div>
</div>
<div>
<h4 class="font-medium text-gray-700 mb-2">Advanced Actions</h4>
<div class="grid grid-cols-2 gap-3">
<button class="bg-blue-100 text-blue-700 hover:bg-blue-200 py-2 px-4 rounded-lg flex items-center justify-center gap-2">
<i data-feather="refresh-cw" class="w-4 h-4"></i>
Refresh Status
</button>
<button class="bg-green-100 text-green-700 hover:bg-green-200 py-2 px-4 rounded-lg flex items-center justify-center gap-2">
<i data-feather="zap" class="w-4 h-4"></i>
Start Charging
</button>
</div>
</div>
</div>
<div class="mt-6 flex justify-end">
<button id="closeModalBtn" class="bg-gray-100 hover:bg-gray-200 text-gray-800 font-medium py-2 px-6 rounded-lg">
Close
</button>
</div>
</div>
`;
document.body.appendChild(modal);
feather.replace();
const closeModal = () => {
document.body.removeChild(modal);
};
modal.querySelector('#closeModal').addEventListener('click', closeModal);
modal.querySelector('#closeModalBtn').addEventListener('click', closeModal);
modal.addEventListener('click', (e) => {
if (e.target === modal) {
closeModal();
}
});
}, 500);
}
// Refresh charge points
function refreshChargePoints() {
// Silent refresh: no notification
loadChargePoints();
}
// Add refresh button to the UI
function addRefreshButton() {
const refreshBtn = document.createElement('button');
refreshBtn.id = 'refreshChargePointsBtn';
refreshBtn.className = 'fixed bottom-24 right-6 z-10 bg-white rounded-full p-3 shadow-lg hover:shadow-xl transition-all duration-300 flex items-center justify-center';
refreshBtn.innerHTML = '<i data-feather="refresh-cw" class="w-6 h-6 text-blue-600"></i>';
refreshBtn.title = 'Refresh Charge Points';
refreshBtn.style.width = '56px';
refreshBtn.style.height = '56px';
refreshBtn.addEventListener('click', refreshChargePoints);
document.body.appendChild(refreshBtn);
feather.replace();
}
// Initialize when DOM is loaded
document.addEventListener('DOMContentLoaded', function() {
initMap();
addRefreshButton();
// Add refresh button to user menu component
document.addEventListener('userMenuReady', function() {
const userMenu = document.querySelector('user-circle-menu');
if (userMenu && userMenu.shadowRoot) {
// We'll add a refresh option to the user menu via event
setTimeout(() => {
// Add global refresh function
window.refreshChargePoints = refreshChargePoints;
// Also expose auto‑refresh controls
window.startAutoRefresh = startAutoRefresh;
window.stopAutoRefresh = stopAutoRefresh;
window.toggleAutoRefresh = toggleAutoRefresh;
}, 100);
}
});
// Auto‑refresh indicator
const indicator = document.createElement('div');
indicator.id = 'autoRefreshIndicator';
indicator.className = 'fixed bottom-6 right-6 z-10 bg-green-100 text-green-800 text-xs font-medium px-3 py-2 rounded-full shadow flex items-center space-x-2';
indicator.innerHTML = `
<div class="w-2 h-2 bg-green-500 rounded-full animate-pulse"></div>
<span>Auto‑refresh every 10s</span>
`;
document.body.appendChild(indicator);
});
// Show notification function
function showNotification(message) {
// Create notification element
const notification = document.createElement('div');
notification.className = 'fixed top-6 right-6 z-50 bg-white rounded-xl shadow-2xl p-4 border-l-4 border-blue-500 transform transition-all duration-300 translate-x-full';
notification.innerHTML = `
<div class="flex items-center">
<div class="w-10 h-10 bg-blue-100 rounded-full flex items-center justify-center mr-3">
<i data-feather="battery-charging" class="text-blue-600"></i>
</div>
<div>
<p class="font-semibold text-gray-800">Charge Points</p>
<p class="text-gray-600 text-sm">${message}</p>
</div>
</div>
`;
// Add to DOM
document.body.appendChild(notification);
// Trigger feather icons replacement
feather.replace();
// Animate in
setTimeout(() => {
notification.classList.remove('translate-x-full');
notification.classList.add('translate-x-0');
}, 10);
// Auto remove after 3 seconds
setTimeout(() => {
notification.classList.remove('translate-x-0');
notification.classList.add('translate-x-full');
setTimeout(() => {
document.body.removeChild(notification);
}, 300);
}, 3000);
}
|