// ===============================
// 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);
// ===============================
// デバイスID(固定保存)
// ===============================
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 = {};
const DEFAULT_LAT = 35.685175;
const DEFAULT_LNG = 139.752799;
// ===============================
// URLパラメータ
// ===============================
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],
popupAnchor: [0, -40]
});
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],
popupAnchor: [0, -40]
});
// ===============================
// 現在地取得
// ===============================
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);
userMarker.bindPopup(`あなた(${currentUser})`);
}
// ===============================
// 自分の位置を保存(1件だけ)
// ===============================
async function saveMyLocation(lat, lng) {
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,
});
}
// ===============================
// メンバー一覧表示
// ===============================
function showMemberList(latestByDevice) {
const list = document.getElementById("memberList");
list.innerHTML = "";
Object.values(latestByDevice).forEach((row) => {
const li = document.createElement("li");
// オンライン判定(10秒以内)
const updated = new Date(row.updated_at);
const now = new Date();
const diff = (now - updated) / 1000;
li.classList.add(diff < 10 ? "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) {
const el = marker._icon;
el.classList.add("bounce-pin");
setTimeout(() => el.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 || !data) return;
// 最新データを1デバイス1件に
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: null,
lng: null,
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;
const mk = L.marker([row.lat, row.lng], { icon: otherIcon }).addTo(map);
mk._myDeviceId = row.device_id;
otherMarkers.push(mk);
});
}
// ===============================
// main
// ===============================
async function main() {
loadParams();
let lat = DEFAULT_LAT;
let lng = DEFAULT_LNG;
try {
const pos = await getPosition();
lat = pos.latitude;
lng = pos.longitude;
} catch {}
initMap(lat, lng);
await saveMyLocation(lat, lng);
await showOtherUsers();
// 2秒ごとに更新
setInterval(showOtherUsers, 2000);
// 退出ボタン
document.getElementById("exitBtn").onclick = () => {
location.href = "index.html";
};
}
window.addEventListener("DOMContentLoaded", main);