// ===================================
// 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 isHost = false;
let map;
let selfMarker = null;
let otherMarkers = [];
let latestByDevice = {};
let allMembers = [];
let lastLat = null;
let lastLng = null;
// 駅関連
let stationMarkers = [];
// 目的地関連
let targetMarker = null;
let targetLat = null;
let targetLng = null;
// ===================================
// URL パラメータ読み込み
// ===================================
function loadParams() {
const p = new URLSearchParams(location.search);
currentGroup = p.get("group") || "";
currentUser = p.get("user") || "";
const hostParam = p.get("host");
isHost = hostParam === "1" || hostParam === "true";
const gSpan = document.getElementById("groupName");
const uSpan = document.getElementById("userName");
const hostLabel = document.getElementById("hostStatus");
if (gSpan) gSpan.textContent = currentGroup;
if (uSpan) uSpan.textContent = currentUser;
if (hostLabel) {
hostLabel.textContent = isHost ? "あなたはホストです" : "一般メンバーです";
}
localStorage.setItem("group", currentGroup);
localStorage.setItem("userName", currentUser);
}
// ===================================
// 位置情報取得
// ===================================
function getPosition() {
return new Promise((resolve, reject) => {
navigator.geolocation.getCurrentPosition(
(pos) => resolve(pos.coords),
(err) => reject(err),
{ enableHighAccuracy: true }
);
});
}
// ===================================
// 地図初期化
// ===================================
function initMap(lat, lng) {
map = L.map("map").setView([lat, lng], 16);
L.tileLayer("https://tile.openstreetmap.org/{z}/{x}/{y}.png", {
maxZoom: 19,
}).addTo(map);
// ホストだけ目的地設定
map.on("click", async (e) => {
if (!isHost) return;
const newLat = e.latlng.lat;
const newLng = e.latlng.lng;
targetLat = newLat;
targetLng = newLng;
if (targetMarker) map.removeLayer(targetMarker);
targetMarker = L.marker([targetLat, targetLng]).addTo(map);
await supa.from("shared_target").upsert({
group_name: currentGroup,
lat: targetLat,
lng: targetLng,
});
const box = document.getElementById("targetInfo");
if (box) box.textContent = "目的地を設定しました!";
});
}
// ===================================
// 自分の位置を保存
// ===================================
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 createLabeledMarker(lat, lng, name, isSelf) {
const pinUrl = isSelf
? "https://raw.githubusercontent.com/pointhi/leaflet-color-markers/master/img/marker-icon-green.png"
: "https://raw.githubusercontent.com/pointhi/leaflet-color-markers/master/img/marker-icon-gold.png";
const html = `
<div class="pin-wrapper">
<img src="${pinUrl}" class="pin-img">
<div class="pin-label">${name}</div>
</div>
`;
return L.marker([lat, lng], {
icon: L.divIcon({
className: "custom-pin",
html: html,
iconSize: [32, 32],
iconAnchor: [16, 32],
}),
});
}
function renderSelfMarker() {
if (selfMarker) map.removeLayer(selfMarker);
selfMarker = createLabeledMarker(lastLat, lastLng, currentUser, true);
selfMarker.addTo(map);
}
// ===================================
// メンバー一覧
// ===================================
function showMemberList(latestByDevice) {
const list = document.getElementById("memberList");
if (!list) return;
Object.values(latestByDevice).forEach((row) => {
if (!allMembers.some((m) => m.device_id === row.device_id)) {
allMembers.push({
device_id: row.device_id,
user_name: row.user_name,
});
}
});
allMembers.forEach((member) => {
let li = list.querySelector(`li[data-id="${member.device_id}"]`);
if (!li) {
li = document.createElement("li");
li.dataset.id = member.device_id;
li.innerHTML = `
<div class="member-icon"></div>
<div class="member-name"></div>
`;
list.appendChild(li);
}
const row = latestByDevice[member.device_id];
const nameElem = li.querySelector(".member-name");
if (nameElem) nameElem.textContent = member.user_name;
let online = false;
if (row && row.updated_at) {
const diff = (Date.now() - new Date(row.updated_at)) / 1000;
online = diff < 6;
}
li.classList.toggle("online", online);
li.classList.toggle("offline", !online);
});
}
// ===================================
// ⭐ ホスト自動交代機能(方法1)
// ===================================
async function checkHostAuto() {
const { data: group } = await supa
.from("groups")
.select("*")
.eq("group_name", currentGroup)
.maybeSingle();
if (!group) return;
const hostName = group.host_name;
// 現ホストが存在するか?
const hostExists = Object.values(latestByDevice).some(
(row) => row.user_name === hostName
);
if (hostExists) return; // ホスト生存 → OK
// ホストが不在 → 新ホストを決める(最新更新の人)
const newest = Object.values(latestByDevice).sort((a, b) => {
return new Date(b.updated_at) - new Date(a.updated_at);
})[0];
if (!newest) return; // 誰もいない
await supa
.from("groups")
.update({ host_name: newest.user_name })
.eq("group_name", currentGroup);
console.log("ホスト不在のため自動交代:", newest.user_name);
// 自分が新ホストなら isHost を更新
if (newest.user_name === currentUser) {
isHost = true;
document.getElementById("hostStatus").textContent = "あなたはホストです";
}
}
// ===================================
// 他ユーザー表示
// ===================================
async function showOtherUsers() {
const { data } = await supa
.from("locations")
.select("*")
.eq("group_name", currentGroup)
.order("updated_at", { ascending: false });
latestByDevice = {};
(data || []).forEach((r) => {
if (!latestByDevice[r.device_id]) latestByDevice[r.device_id] = r;
});
showMemberList(latestByDevice);
// ⭐ ホスト自動交代をここで実行
await checkHostAuto();
// ピン更新
otherMarkers.forEach((m) => map.removeLayer(m));
otherMarkers = [];
Object.values(latestByDevice).forEach((row) => {
if (row.device_id === deviceId) return;
const mk = createLabeledMarker(row.lat, row.lng, row.user_name, false);
mk.addTo(map);
otherMarkers.push(mk);
});
}
// ===================================
// 駅関連
// ===================================
async function fetchStationsAround(lat, lng) {
const query = `
[out:json];
node["railway"="station"](around:5000,${lat},${lng});
out;
`;
const res = await fetch(
"https://overpass-api.de/api/interpreter?data=" +
encodeURIComponent(query)
);
const json = await res.json();
return json.elements || [];
}
async function loadStations() {
const box = document.getElementById("nearestBox");
if (!box) return;
try {
const stations = await fetchStationsAround(lastLat, lastLng);
stationMarkers.forEach((m) => map.removeLayer(m));
stationMarkers = [];
if (stations.length === 0) {
box.textContent = "駅が見つかりませんでした。";
return;
}
let nearest = null;
let nearestDist = Infinity;
stations.forEach((st) => {
const name = st.tags?.name || "駅名不明";
const d = distanceMeters(lastLat, lastLng, st.lat, st.lon);
if (d < nearestDist) {
nearestDist = d;
nearest = { name, lat: st.lat, lng: st.lon };
}
const mk = L.marker([st.lat, st.lon]).addTo(map);
mk.bindPopup(name + "駅");
stationMarkers.push(mk);
});
box.textContent =
"最寄り駅:" +
nearest.name +
"(約 " +
(nearestDist / 1000).toFixed(2) +
" km)";
} catch {
box.textContent = "駅情報を取得できませんでした。";
}
}
// ===================================
// 共有目的地
// ===================================
async function loadSharedTarget() {
const box = document.getElementById("targetInfo");
const { data } = await supa
.from("shared_target")
.select("*")
.eq("group_name", currentGroup)
.maybeSingle();
if (!data) return;
if (targetLat === data.lat && targetLng === data.lng) return;
targetLat = data.lat;
targetLng = data.lng;
if (targetMarker) map.removeLayer(targetMarker);
targetMarker = L.marker([targetLat, targetLng]).addTo(map);
box.textContent = "目的地が共有されました!";
}
// ===================================
// チャット
// ===================================
async function loadMessages() {
const chatList = document.getElementById("chatList");
const { data } = await supa
.from("messages")
.select("*")
.eq("group_name", currentGroup)
.order("created_at", { ascending: true });
chatList.innerHTML = (data || [])
.map((m) => `<div><strong>${m.user_name}:</strong> ${m.message}</div>`)
.join("");
chatList.scrollTop = chatList.scrollHeight;
}
async function sendMessage() {
const input = document.getElementById("chatInput");
const text = input.value.trim();
if (!text) return;
await supa.from("messages").insert({
group_name: currentGroup,
user_name: currentUser,
message: text,
});
input.value = "";
loadMessages();
}
// ===================================
// メイン
// ===================================
async function main() {
loadParams();
let lat = 35.681236;
let lng = 139.767125;
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();
loadStations();
loadSharedTarget();
loadMessages();
setInterval(async () => {
const pos = await getPosition();
lastLat = pos.latitude;
lastLng = pos.longitude;
renderSelfMarker();
await saveMyLocation(lastLat, lastLng);
}, 2000);
setInterval(showOtherUsers, 1200);
setInterval(loadSharedTarget, 10000);
setInterval(loadMessages, 2000);
document.getElementById("exitBtn").onclick = () => {
location.href = "index.html";
};
document.getElementById("chatSend").onclick = sendMessage;
document.getElementById("chatInput").addEventListener("keydown", (e) => {
if (e.key === "Enter") sendMessage();
});
setTimeout(() => map.invalidateSize(), 500);
}
window.addEventListener("DOMContentLoaded", main);