fix(dashboard): geocode fires on first GPS fix, gated by distance not timer
Co-authored-by: Copilot <[email protected]>
This commit is contained in:
+10
-12
@@ -187,7 +187,7 @@ socket.on('obd_error', function (data) {
|
||||
let mapCentered = false;
|
||||
let _lastLat = null, _lastLon = null;
|
||||
let _lastGeoLat = null, _lastGeoLon = null;
|
||||
let _geocodeTimer = null;
|
||||
let _geocodePending = false;
|
||||
|
||||
const _recenterBtn = document.getElementById('btn-recenter');
|
||||
_recenterBtn.addEventListener('click', function () {
|
||||
@@ -197,20 +197,16 @@ _recenterBtn.addEventListener('click', function () {
|
||||
});
|
||||
|
||||
function reverseGeocode(lat, lon) {
|
||||
if (_geocodePending) return;
|
||||
_geocodePending = true;
|
||||
const el = document.getElementById('gps-location-name');
|
||||
const fallback = `${lat.toFixed(5)}, ${lon.toFixed(5)}`;
|
||||
const ctrl = new AbortController();
|
||||
const t = setTimeout(() => ctrl.abort(), 6000);
|
||||
fetch(`/api/geocode?lat=${lat}&lon=${lon}`, { signal: ctrl.signal })
|
||||
.then(r => { clearTimeout(t); return r.ok ? r.json() : null; })
|
||||
.then(data => { el.textContent = (data && data.label) ? data.label : fallback; })
|
||||
.catch(() => { clearTimeout(t); el.textContent = fallback; });
|
||||
}
|
||||
|
||||
function _movedEnough(lat, lon) {
|
||||
if (_lastGeoLat === null) return true;
|
||||
// ~0.0005 deg ≈ 50m
|
||||
return Math.abs(lat - _lastGeoLat) > 0.0005 || Math.abs(lon - _lastGeoLon) > 0.0005;
|
||||
.then(data => { _geocodePending = false; el.textContent = (data && data.label) ? data.label : fallback; })
|
||||
.catch(() => { clearTimeout(t); _geocodePending = false; el.textContent = fallback; });
|
||||
}
|
||||
|
||||
socket.on('gps_location', function(data) {
|
||||
@@ -233,12 +229,14 @@ socket.on('gps_location', function(data) {
|
||||
_lastLat = lat;
|
||||
_lastLon = lon;
|
||||
_recenterBtn.hidden = false;
|
||||
// Geocode when moved >50m, throttled to at most once every 15s
|
||||
if (!_geocodeTimer && _movedEnough(lat, lon)) {
|
||||
// Geocode on first fix or after moving >50m (~0.0005 deg)
|
||||
const moved = _lastGeoLat === null
|
||||
|| Math.abs(lat - _lastGeoLat) > 0.0005
|
||||
|| Math.abs(lon - _lastGeoLon) > 0.0005;
|
||||
if (moved) {
|
||||
_lastGeoLat = lat;
|
||||
_lastGeoLon = lon;
|
||||
reverseGeocode(lat, lon);
|
||||
_geocodeTimer = setTimeout(() => { _geocodeTimer = null; }, 15000);
|
||||
}
|
||||
}
|
||||
});
|
||||
|
||||
Reference in New Issue
Block a user