Newer
Older
2025-shino / map4.js
// ===================================
// 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 currentHostName = ""; // Supabase に保存されているホスト名

let map;
let selfMarker = null;
let otherMarkers = [];
let latestByDevice = {};
let allMembers = [];
let lastLat = null;
let lastLng = null;
let targetMarker = null;

// 駅関連
let stationMarkers = [];

// 待ち合わせ関連
let targetLat = null;
let targetLng = null;

// ===================================
// 待ち合わせピン(violet)
// ===================================
const meetIcon = L.icon({
  iconUrl:
    "https://raw.githubusercontent.com/pointhi/leaflet-color-markers/master/img/marker-icon-violet.png",
  shadowUrl:
    "https://cdnjs.cloudflare.com/ajax/libs/leaflet/1.7.1/images/marker-shadow.png",
  iconSize: [25, 41],
  iconAnchor: [12, 41],
});

// ===================================
// 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;

  localStorage.setItem("group", currentGroup);
  localStorage.setItem("userName", currentUser);

  const hostLabel = document.getElementById("hostStatus");
  if (hostLabel) {
    hostLabel.textContent = isHost ? "あなたはホストです" : "一般メンバーです";
  }
}

// ===================================
// 現在位置取得
// ===================================
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;

    if (targetLat !== null && targetLng !== null) {
      const ok = confirm("待ち合わせ場所を置き直しますか?");
      if (!ok) return;
    }

    targetLat = newLat;
    targetLng = newLng;

    if (targetMarker) map.removeLayer(targetMarker);
    targetMarker = L.marker([targetLat, targetLng], { icon: meetIcon }).addTo(
      map
    );

    await supa.from("shared_target").upsert({
      group_name: currentGroup,
      lat: targetLat,
      lng: targetLng,
    });

    document.getElementById("targetInfo").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 renderSelfMarker() {
  if (!map || lastLat === null || lastLng === null) return;

  if (selfMarker) map.removeLayer(selfMarker);

  selfMarker = createLabeledMarker(lastLat, lastLng, currentUser, true);
  selfMarker.addTo(map);
}

// ===================================
// ピン生成(自分:緑 / 他人:金)
// ===================================
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-box">
      <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: [40, 50], // ピン+ラベルの領域
      iconAnchor: [20, 50], // 下中央を位置座標に合わせる
    }),
  });
}

// ===================================
// 距離計算(修正版)
// ===================================
function distanceMeters(lat1, lng1, lat2, lng2) {
  const R = 6371000;
  const toRad = (deg) => (deg * Math.PI) / 180;

  const dLat = toRad(lat2 - lat1);
  const dLng = toRad(lng2 - lng1); // ← 正しく lng2 - lng1

  const a =
    Math.sin(dLat / 2) ** 2 +
    Math.cos(toRad(lat1)) *
      Math.cos(toRad(lat2)) *
      Math.sin(dLng / 2) ** 2;

  return R * 2 * Math.atan2(Math.sqrt(a), Math.sqrt(1 - a));
}

// ===================================
// メンバー一覧(ピン色連動 + イニシャルアイコン)
// ===================================
function showMemberList(latestByDevice) {
  const list = document.getElementById("memberList");
  list.innerHTML = "";

  // 新規参加の人を順番固定で追加
  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) => {
    const row = latestByDevice[member.device_id];
    const li = document.createElement("li");

    const online =
      row && row.updated_at
        ? (Date.now() - new Date(row.updated_at)) / 1000 < 6
        : false;

    li.classList.toggle("online", online);
    li.classList.toggle("offline", !online);

    // 👑 ホスト表示
    const crown = member.user_name === currentHostName ? "👑 " : "";

    // イニシャル1文字
    const initial = member.user_name.charAt(0);

    // ピン色と連携(自分=緑、他人=金)
    const bgColor = member.device_id === deviceId ? "#4CAF50" : "#FFD700";

    li.innerHTML = `
      <div class="member-icon" style="
        background:${bgColor};
        display:flex;
        align-items:center;
        justify-content:center;
        color:white;
        font-weight:bold;
        font-size:16px;
      ">${initial}</div>
      <span class="member-name">${crown}${member.user_name}</span>
    `;

    // クリックでその人に移動
    li.addEventListener("click", () => {
      const latestRow = latestByDevice[member.device_id];
      if (!latestRow) return;
      map.setView([latestRow.lat, latestRow.lng], 17, { animate: true });
    });

    list.appendChild(li);
  });
}

// ===================================
// ホスト自動交代 + 表示更新
// ===================================
async function checkHostAuto() {
  const { data: group } = await supa
    .from("groups")
    .select("*")
    .eq("group_name", currentGroup)
    .maybeSingle();

  if (!group) return;
  if (group.is_active === false) return;

  currentHostName = group.host_name;

  const onlineUsers = Object.values(latestByDevice).filter((r) => {
    return (Date.now() - new Date(r.updated_at)) / 1000 < 6;
  });

  const hostOnline = onlineUsers.some(
    (u) => u.user_name === currentHostName
  );

  if (hostOnline) {
    isHost = currentUser === currentHostName;
  } else {
    if (onlineUsers.length > 0) {
      const newHost = onlineUsers.sort(
        (a, b) => new Date(b.updated_at) - new Date(a.updated_at)
      )[0];

      await supa
        .from("groups")
        .update({ host_name: newHost.user_name })
        .eq("group_name", currentGroup);

      currentHostName = newHost.user_name;
      isHost = currentUser === currentHostName;
    }
  }

  const hostLabel = document.getElementById("hostStatus");
  if (hostLabel) {
    hostLabel.textContent = isHost ? "あなたはホストです" : "一般メンバーです";
  }

  const disbandBtn = document.getElementById("disbandBtn");
  if (disbandBtn) {
    disbandBtn.style.display = isHost ? "inline-block" : "none";
  }
}

// ===================================
// グループ解散
// ===================================
async function disbandGroup() {
  if (!isHost) {
    alert("グループを解散できるのはホストだけです。");
    return;
  }

  const ok = confirm(
    "このグループを解散しますか?\n※チャットや位置情報の履歴は残り、リアルタイム共有だけ停止されます。"
  );
  if (!ok) return;

  try {
    await supa
      .from("groups")
      .update({ is_active: false })
      .eq("group_name", currentGroup);

    alert("グループを解散しました。履歴ページに移動します。");
    location.href =
      "archive.html?group=" + encodeURIComponent(currentGroup);
  } catch (e) {
    console.error("グループ解散エラー:", e);
    alert("解散処理に失敗しました。");
  }
}

// ===================================
// グループ状態監視
// ===================================
async function checkGroupActive() {
  const { data, error } = await supa
    .from("groups")
    .select("is_active")
    .eq("group_name", currentGroup)
    .maybeSingle();

  if (error) {
    console.error("グループ状態チェックエラー:", error);
    return;
  }

  if (!data || data.is_active === false) {
    alert("このグループは解散されました。(履歴ページに移動します)");
    location.href =
      "archive.html?group=" + encodeURIComponent(currentGroup);
  }
}

// ===================================
// 全員待ち合わせ到着チェック
// ===================================
async function checkAllArrived() {
  if (targetLat === null) return;

  const users = Object.values(latestByDevice);
  if (users.length === 0) return;

  const allArrived = users.every((u) => {
    const d = distanceMeters(u.lat, u.lng, targetLat, targetLng);
    return d < 120;
  });

  if (!allArrived) return;

  document.getElementById("targetInfo").innerHTML = `
    🎉 全員が待ち合わせ場所に到着しました! 🎉
    <br><small>ホストは新しい待ち合わせ場所を設定できます</small>
  `;

  targetLat = null;
  targetLng = null;

  if (targetMarker) {
    map.removeLayer(targetMarker);
    targetMarker = null;
  }

  await supa.from("shared_target").delete().eq("group_name", currentGroup);
}

// ===================================
// 全メンバーの位置表示
// ===================================
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;
  });

  await checkHostAuto();
  showMemberList(latestByDevice);
  await checkAllArrived();

  otherMarkers.forEach((m) => map.removeLayer(m));
  otherMarkers = [];
  Object.values(latestByDevice).forEach((r) => {
    if (r.device_id === deviceId) return;

    const mk = createLabeledMarker(r.lat, r.lng, r.user_name, false);
    mk.addTo(map);
    otherMarkers.push(mk);
  });
}

// ===================================
// 待ち合わせ距離表示
// ===================================
function showDistanceToTarget() {
  if (targetLat === null) return;

  const d = distanceMeters(lastLat, lastLng, targetLat, targetLng);
  const km = (d / 1000).toFixed(2);

  document.getElementById("targetInfo").innerHTML =
    `待ち合わせ場所まで 約 <b>${km} km</b>`;
}

// ===================================
// 駅情報取得(5km範囲)
// ===================================
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)
  );

  return (await res.json()).elements || [];
}

async function loadStations() {
  const box = document.getElementById("nearestBox");

  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) {
      nearest = { name, lat: st.lat, lng: st.lon };
      nearestDist = d;
    }

    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)";
}

// ===================================
// 共有待ち合わせ読み込み
// ===================================
async function loadSharedTarget() {
  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], { icon: meetIcon }).addTo(
    map
  );

  document.getElementById("targetInfo").textContent =
    "待ち合わせ場所が共有されました!";
}

// ===================================
// チャット(LINE風)
// ===================================
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) => {
      const isMe = m.user_name === currentUser;
      const side = isMe ? "chat-right" : "chat-left";

      return `
      <div class="chat-line">
        <div class="chat-bubble ${side}">
          ${isMe ? "" : `<strong>${m.user_name}</strong><br>`}
          ${m.message}
        </div>
      </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 () => {
    try {
      const pos = await getPosition();
      lastLat = pos.latitude;
      lastLng = pos.longitude;
      renderSelfMarker();
      await saveMyLocation(lastLat, lastLng);
      showDistanceToTarget();
    } catch {}
  }, 2000);

  setInterval(showOtherUsers, 1200);
  setInterval(loadSharedTarget, 10000);
  setInterval(loadMessages, 2000);
  setInterval(checkGroupActive, 3000);

  const exitBtn = document.getElementById("exitBtn");
  if (exitBtn) {
    exitBtn.onclick = () => (location.href = "index.html");
  }

  const disbandBtn = document.getElementById("disbandBtn");
  if (disbandBtn) {
    disbandBtn.onclick = disbandGroup;
  }

  document.getElementById("chatSend").onclick = sendMessage;

  document
    .getElementById("chatInput")
    .addEventListener("keydown", (e) => {
      if (e.key === "Enter") sendMessage();
    });

  setTimeout(() => map.invalidateSize(), 500);
}

// -----------------------------------
// DOMContentLoaded
// -----------------------------------
window.addEventListener("DOMContentLoaded", async () => {
  const params = new URLSearchParams(location.search);
  const groupNameFromUrl = params.get("group");
  const userFromUrl = params.get("user");

  const { data: group } = await supa
    .from("groups")
    .select("*")
    .eq("group_name", groupNameFromUrl)
    .maybeSingle();

  if (!group) {
    alert("このグループは存在しません。");
    location.href = "index.html";
    return;
  }

  if (group.is_active === false) {
    alert("このグループは解散されています。履歴ページを表示します。");
    location.href =
      "archive.html?group=" + encodeURIComponent(groupNameFromUrl || "");
    return;
  }

  currentHostName = group.host_name;
  isHost = currentHostName === userFromUrl;

  const hostLabel = document.getElementById("hostStatus");
  if (hostLabel)
    hostLabel.textContent = isHost ? "あなたはホストです" : "一般メンバーです";

  const disbandBtn = document.getElementById("disbandBtn");
  if (disbandBtn) {
    disbandBtn.style.display = isHost ? "inline-block" : "none";
  }

  main();
});