// ===============================
// Supabase 設定
// ===============================
const SUPABASE_URL = "https://ogtlmtnjkpsxsqzqlacj.supabase.co";
const SUPABASE_KEY =
"eyJhbGciOiJIUzI1NiIsInR5cCI6IkpXVCJ9.eyJpc3MiOiJzdXBhYmFzZSIsInJlZiI6Im9ndGxtdG5qa3BzeHNxenFsYWNqIiwicm9sZSI6ImFub24iLCJpYXQiOjE3NjMyOTU3NjUsImV4cCI6MjA3ODg3MTc2NX0.JnCE7oUQwrSgGqiu-QRbwnaLBZrO8JX1_RUb37VIMFI";
const supa = window.supabase.createClient(SUPABASE_URL, SUPABASE_KEY);
// ===============================
let deviceId = localStorage.getItem("deviceId");
if (!deviceId) {
deviceId = crypto.randomUUID();
localStorage.setItem("deviceId", deviceId);
}
let currentGroup = "";
let currentUser = "";
let map;
let userMarker;
let otherMarkers = [];
let latestByDevice = {};
let lastLat = null;
let lastLng = null;
const DEFAULT_LAT = 35.685175;
const DEFAULT_LNG = 139.752799;
// ===============================
function loadParams() {
const params = new URLSearchParams(location.search);
currentGroup = params.get("group") || "";
currentUser = params.get("user") || "";
document.getElementById("groupName").textContent = currentGroup;
document.getElementById("userName").textContent = currentUser;
}
// ===============================
const myIcon = L.icon({
iconUrl: "https://raw.githubusercontent.com/pointhi/leaflet-color-markers/master/img/marker-icon-blue.png",
iconSize: [30, 45],
iconAnchor: [15, 45],
});
const otherIcon = L.icon({
iconUrl: "https://raw.githubusercontent.com/pointhi/leaflet-color-markers/master/img/marker-icon-red.png",
iconSize: [30, 45],
iconAnchor: [15, 45],
});
// ===============================
function getPosition() {
return new Promise((resolve, reject) => {
navigator.geolocation.getCurrentPosition(
(pos) => resolve(pos.coords),
reject,
{ enableHighAccuracy: true }
);
});
}
// ===============================
function initMap(lat, lng) {
map = L.map("map").setView([lat, lng], 15);
L.tileLayer("https://tile.openstreetmap.org/{z}/{x}/{y}.png", {
maxZoom: 19,
}).addTo(map);
userMarker = L.marker([lat, lng], { icon: myIcon }).addTo(map);
}
// ===============================
async function saveMyLocation(lat, lng) {
try {
await supa
.from("locations")
.delete()
.eq("group_name", currentGroup)
.eq("device_id", deviceId);
await supa.from("locations").insert({
group_name: currentGroup,
user_name: currentUser,
device_id: deviceId,
lat,
lng,
});
} catch (e) {
console.warn("位置保存失敗:", e);
}
}
// ===============================
function showMemberList(latestByDevice) {
const list = document.getElementById("memberList");
list.innerHTML = "";
Object.values(latestByDevice).forEach((row) => {
const li = document.createElement("li");
// ★ オンライン判定:30秒以内
const updated = new Date(row.updated_at);
const now = new Date();
const diff = (now - updated) / 1000;
li.classList.add(diff < 30 ? "online" : "offline");
const icon = document.createElement("div");
icon.className = "member-icon";
li.appendChild(icon);
li.append(row.user_name);
li.addEventListener("click", () => {
if (row.lat && row.lng) {
map.setView([row.lat, row.lng], 16, { animate: true });
const marker = otherMarkers.find(m => m._myDeviceId === row.device_id);
if (marker && marker._icon) {
marker._icon.classList.add("bounce-pin");
setTimeout(() => marker._icon.classList.remove("bounce-pin"), 600);
}
}
});
list.appendChild(li);
});
}
// ===============================
async function showOtherUsers() {
const { data, error } = await supa
.from("locations")
.select("*")
.eq("group_name", currentGroup)
.order("updated_at", { ascending: false });
if (error || !Array.isArray(data)) return;
latestByDevice = {};
for (const row of data) {
if (!latestByDevice[row.device_id]) {
latestByDevice[row.device_id] = row;
}
}
// 自分が抜け落ちるのを防ぐ
if (!latestByDevice[deviceId]) {
latestByDevice[deviceId] = {
user_name: currentUser,
device_id: deviceId,
lat: lastLat,
lng: lastLng,
updated_at: new Date().toISOString()
};
}
showMemberList(latestByDevice);
otherMarkers.forEach((m) => map.removeLayer(m));
otherMarkers = [];
Object.values(latestByDevice).forEach((row) => {
if (row.device_id === deviceId) return;
if (row.lat == null || row.lng == null) return;
const mk = L.marker([row.lat, row.lng], { icon: otherIcon }).addTo(map);
mk._myDeviceId = row.device_id;
otherMarkers.push(mk);
});
}
// ===============================
async function main() {
loadParams();
let lat = DEFAULT_LAT;
let lng = DEFAULT_LNG;
try {
const pos = await getPosition();
lat = pos.latitude;
lng = pos.longitude;
} catch {}
lastLat = lat;
lastLng = lng;
initMap(lat, lng);
await saveMyLocation(lastLat, lastLng);
await showOtherUsers();
// ★ 位置更新を 10秒ごとに(安定性向上)
setInterval(async () => {
try {
const pos = await getPosition();
lastLat = pos.latitude;
lastLng = pos.longitude;
await saveMyLocation(lastLat, lastLng);
} catch {}
}, 10000);
// 他ユーザー 2秒ごと更新
setInterval(showOtherUsers, 2000);
const exitBtn = document.getElementById("exitBtn");
if (exitBtn) exitBtn.onclick = () => location.href = "index.html";
}
window.addEventListener("DOMContentLoaded", main);