// ===================================
// 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 selfMarker = null;
let otherMarkers = [];
let latestByDevice = {};
let lastLat = null;
let lastLng = null;
const DEFAULT_LAT = 35.685175;
const DEFAULT_LNG = 139.752799;
// ===================================
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) {
return L.icon({
iconUrl:
type === "self"
? "https://maps.gstatic.com/mapfiles/kml/paddle/blu-stars.png"
: "https://raw.githubusercontent.com/pointhi/leaflet-color-markers/master/img/marker-icon-green.png",
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"),
}).addTo(map);
selfMarker.bindPopup(`<b>${currentUser}</b>(あなた)`);
selfMarker.on("click", (e) => {
map.panTo(e.latlng, { animate: true, duration: 0.4 });
selfMarker.openPopup();
});
}
// ===================================
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 diff = (Date.now() - new Date(row.updated_at)) / 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 を発火(中央移動100%)
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) 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 });
latestByDevice = {};
if (!Array.isArray(data)) return;
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"),
}).addTo(map);
mk._myDeviceId = row.device_id;
mk.bindPopup(`<b>${row.user_name}</b>`);
mk.on("click", (e) => {
map.panTo(e.latlng, { animate: true, duration: 0.4 });
mk.openPopup();
});
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);
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);
document.getElementById("exitBtn").onclick =
() => (location.href = "index.html");
// ★ Leaflet の中心ズレを完全修正
setTimeout(() => map.invalidateSize(), 300);
}
window.addEventListener("DOMContentLoaded", main);