prop/assets/js/locate_me_hook.js
Graham McIntire 43b51fdb98 Throttle GPS updates on path page to once per minute
Switch from getCurrentPosition (which looped via push_patch) to
watchPosition with a 60-second throttle. Break the server-side
request_gps loop by skipping re-request when coords already exist.
2026-04-07 14:44:34 -05:00

63 lines
1.8 KiB
JavaScript

export const CopyLink = {
mounted() {
this.el.addEventListener("click", () => {
navigator.clipboard.writeText(window.location.href).then(() => {
const orig = this.el.innerHTML
this.el.innerHTML = '<span class="text-success">Copied!</span>'
setTimeout(() => { this.el.innerHTML = orig }, 1500)
})
})
}
}
export const LocateMe = {
mounted() {
this.watchId = null
this.lastSentAt = 0
this.el.addEventListener("click", () => this.startWatching())
// Also respond to server-pushed request (for source=gps URLs)
this.handleEvent("request_gps", () => this.startWatching())
},
destroyed() {
if (this.watchId !== null) {
navigator.geolocation.clearWatch(this.watchId)
}
},
startWatching() {
if (!navigator.geolocation) {
alert("Geolocation is not supported by this browser")
return
}
// Already watching — don't start another
if (this.watchId !== null) return
this.el.classList.add("loading", "loading-spinner")
this.watchId = navigator.geolocation.watchPosition(
(pos) => {
const now = Date.now()
// Send immediately on first fix, then at most once per minute
if (this.lastSentAt === 0 || now - this.lastSentAt >= 60000) {
this.lastSentAt = now
this.el.classList.remove("loading", "loading-spinner")
this.pushEvent("gps_location", {
lat: pos.coords.latitude,
lon: pos.coords.longitude
})
}
},
(err) => {
this.el.classList.remove("loading", "loading-spinner")
navigator.geolocation.clearWatch(this.watchId)
this.watchId = null
alert("Could not get location: " + err.message)
},
{ enableHighAccuracy: true, timeout: 10000 }
)
}
}