// ===================================
// 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 createLabeledIcon(name, 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.divIcon({
className: "custom-pin",
html: `
<div class="pin-label">${name}</div>
<img src="${pinImg}" class="pin-image">
`,
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: createLabeledIcon(currentUser, "self"),
interactive: true,
bubblingMouseEvents: true,
}).addTo(map);
// ★ クリックで中央へ(アニメなし)
selfMarker.on("click", () => {
map.setView([lastLat, lastLng], 16, { animate: true });
});
}
// ===================================
// 保存
// ===================================
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);
li.addEventListener("click", () => {
if (row.device_id === deviceId) {
map.setView([lastLat, lastLng], 16, { animate: true });
return;
}
const mk = otherMarkers.find((m) => m._myDeviceId === row.device_id);
if (!mk) return;
map.setView([row.lat, row.lng], 16, { animate: true });
});
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: createLabeledIcon(row.user_name, "other"),
interactive: true,
bubblingMouseEvents: true,
}).addTo(map);
mk._myDeviceId = row.device_id;
mk.on("click", () => {
map.setView([row.lat, row.lng], 16, { animate: true });
});
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);