// ===================================
// 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 selfMarker = null;
let otherMarkers = [];
let latestByDevice = {};
let lastLat = null;
let lastLng = null;
const DEFAULT_LAT = 35.685175;
const DEFAULT_LNG = 139.752799;
// ===================================
// URL パラメータ
// ===================================
function loadParams() {
const p = new URLSearchParams(location.search);
currentGroup = p.get("group");
currentUser = p.get("user");
document.getElementById("groupName").textContent = currentGroup;
document.getElementById("userName").textContent = currentUser;
}
// ===================================
// ピンアイコン(常時ラベルなし)
// ===================================
function createIcon(type) {
let pinImg = "";
if (type === "self") {
// 自分 → 青い星
pinImg = "https://maps.gstatic.com/mapfiles/kml/paddle/blu-stars.png";
} else {
// 他人 → ライトグリーン
pinImg =
"https://raw.githubusercontent.com/pointhi/leaflet-color-markers/master/img/marker-icon-green.png";
}
return L.icon({
iconUrl: pinImg,
iconSize: [40, 55],
iconAnchor: [20, 50], // 画像の下あたり
});
}
// ===================================
// 現在地取得
// ===================================
function getPosition() {
return new Promise((res, rej) => {
navigator.geolocation.getCurrentPosition(
(pos) => res(pos.coords),
rej,
{ 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);
}
// ===================================
// 自分のピン描画
// ===================================
function renderSelfMarker() {
if (selfMarker) map.removeLayer(selfMarker);
selfMarker = L.marker([lastLat, lastLng], {
icon: createIcon("self"),
interactive: true,
}).addTo(map);
// popup(吹き出し)
selfMarker.bindPopup(`<b>${currentUser}</b>(あなた)`);
// ★ クリックした位置 e.latlng を使って中央へ
selfMarker.on("click", (e) => {
map.panTo(e.latlng, { animate: true, duration: 0.5 });
selfMarker.openPopup();
});
}
// ===================================
// 自分の位置を Supabase に保存
// ===================================
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");
const updated = new Date(row.updated_at);
const diff = (Date.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);
// ★ メンバー一覧クリック → 対応するピンの click を発火
li.addEventListener("click", () => {
if (row.device_id === deviceId) {
if (selfMarker) {
selfMarker.fire("click");
}
return;
}
const mk = otherMarkers.find((m) => m._myDeviceId === row.device_id);
if (!mk) return;
mk.fire("click");
});
list.appendChild(li);
});
}
// ===================================
// 他ユーザー描画
// ===================================
async function showOtherUsers() {
const { data } = await supa
.from("locations")
.select("*")
.eq("group_name", currentGroup)
.order("updated_at", { ascending: false });
if (!Array.isArray(data)) return;
latestByDevice = {};
for (const row of data) {
if (!latestByDevice[row.device_id]) latestByDevice[row.device_id] = row;
}
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: createIcon("other"),
interactive: true,
}).addTo(map);
mk._myDeviceId = row.device_id;
// popup
mk.bindPopup(`<b>${row.user_name}</b>`);
// ★ ピン直接クリック → e.latlng で中央へ
mk.on("click", (e) => {
map.panTo(e.latlng, { animate: true, duration: 0.5 });
mk.openPopup();
});
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 {}
lastLat = lat;
lastLng = lng;
initMap(lat, lng);
renderSelfMarker();
await saveMyLocation(lat, lng);
await showOtherUsers();
// 自分の位置更新
setInterval(async () => {
try {
const pos = await getPosition();
lastLat = pos.latitude;
lastLng = pos.longitude;
renderSelfMarker();
await saveMyLocation(lastLat, lastLng);
} catch {}
}, 8000);
// 他ユーザー更新
setInterval(showOtherUsers, 2000);
const exit = document.getElementById("exitBtn");
if (exit) exit.onclick = () => (location.href = "index.html");
}
window.addEventListener("DOMContentLoaded", main);