// ESP32 DHT11 Overlay for qgis2web // Place this file in your resources folder and include it in index.html (function() { 'use strict'; // Configuration const ESP32_IP = '192.168.1.100'; // Replace with your ESP32 IP const UPDATE_INTERVAL = 5000; // Update every 5 seconds // Wait for map to be initialized function waitForMap() { if (typeof map !== 'undefined') { initESP32Overlay(); } else { setTimeout(waitForMap, 100); } } function initESP32Overlay() { // Create vector source and layer for ESP32 marker const esp32Source = new ol.source.Vector(); const esp32Layer = new ol.layer.Vector({ source: esp32Source, title: 'ESP32 Sensor', style: new ol.style.Style({ image: new ol.style.Circle({ radius: 8, fill: new ol.style.Fill({color: '#ff0000'}), stroke: new ol.style.Stroke({color: '#ffffff', width: 2}) }), text: new ol.style.Text({ offsetY: -15, fill: new ol.style.Fill({color: '#000'}), stroke: new ol.style.Stroke({color: '#fff', width: 3}), font: 'bold 12px sans-serif' }) }) }); // Add layer to map map.addLayer(esp32Layer); // Fetch and update data function updateSensorData() { fetch(`http://${ESP32_IP}/`) .then(response => response.json()) .then(data => { // Clear existing features esp32Source.clear(); // Create feature const coords = ol.proj.fromLonLat([data.longitude, data.latitude]); const feature = new ol.Feature({ geometry: new ol.geom.Point(coords), temperature: data.temperature, humidity: data.humidity, timestamp: data.timestamp }); // Update style with temperature feature.setStyle(new ol.style.Style({ image: new ol.style.Circle({ radius: 8, fill: new ol.style.Fill({color: '#ff0000'}), stroke: new ol.style.Stroke({color: '#ffffff', width: 2}) }), text: new ol.style.Text({ text: `${data.temperature}°C`, offsetY: -15, fill: new ol.style.Fill({color: '#000'}), stroke: new ol.style.Stroke({color: '#fff', width: 3}), font: 'bold 12px sans-serif' }) })); esp32Source.addFeature(feature); console.log('ESP32 data updated:', data); }) .catch(error => { console.error('Error fetching ESP32 data:', error); }); } // Initial update and set interval updateSensorData(); setInterval(updateSensorData, UPDATE_INTERVAL); // Add popup interaction map.on('click', function(evt) { const feature = map.forEachFeatureAtPixel(evt.pixel, function(feature) { return feature; }); if (feature && feature.get('temperature')) { const popupElement = document.getElementById('popup-content'); if (popupElement) { popupElement.innerHTML = `
Temperature: ${feature.get('temperature')}°C
Humidity: ${feature.get('humidity')}%
`; const popup = new ol.Overlay({ element: document.getElementById('popup'), positioning: 'bottom-center', stopEvent: false, offset: [0, -10] }); map.addOverlay(popup); popup.setPosition(evt.coordinate); } } }); } // Start when DOM is ready if (document.readyState === 'loading') { document.addEventListener('DOMContentLoaded', waitForMap); } else { waitForMap(); } })();