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

// ===================================
// デバイス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;

let isHost = false; // ← Supabase で判定する本物のホスト判定

// 駅関連
let stationMarkers = [];

// 目的地共有関連
let targetMarker = null;
let targetLat = null;
let targetLng = null;
let arrived = false;
let lastShownDistance = null;

// デフォルト(皇居)
const DEFAULT_LAT = 35.681236;
const DEFAULT_LNG = 139.767125;

// ===================================
// アイコン
// ===================================
const stationIcon = L.icon({
  iconUrl:
    "https://raw.githubusercontent.com/pointhi/leaflet-color-markers/master/img/marker-icon-blue.png",
  shadowUrl:
    "https://cdnjs.cloudflare.com/ajax/libs/leaflet/1.7.1/images/marker-shadow.png",
  iconSize: [25, 41],
  iconAnchor: [12, 41],
});

const targetIcon = L.icon({
  iconUrl:
    "https://raw.githubusercontent.com/pointhi/leaflet-color-markers/master/img/marker-icon-red.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;
}

// ===================================
// 本物のホスト判定(Supabase groups.host_name)
// ===================================
async function decideHost() {
  const { data, error } = await supa
    .from("groups")
    .select("host_name")
    .eq("group_name", currentGroup)
    .maybeSingle();

  if (error) {
    console.error("ホスト情報の取得に失敗:", error);
    isHost = false;
  } else if (data && data.host_name) {
    isHost = data.host_name === currentUser;
  } else {
    isHost = false;
  }

  // 画面表示へ反映
  const hostLabel = document.getElementById("hostStatus");
  if (hostLabel)
    hostLabel.textContent = isHost ? "あなたはホストです" : "一般メンバーです";
}

// ===================================
// 小型ピン
// ===================================
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 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], 16);
  L.tileLayer("https://tile.openstreetmap.org/{z}/{x}/{y}.png", {
    maxZoom: 19,
  }).addTo(map);

  // ホストだけ目的地を設定可能
  map.on("click", async (e) => {
    if (!isHost) {
      alert("目的地を設定できるのはホストだけです!");
      return;
    }

    const newLat = e.latlng.lat;
    const newLng = e.latlng.lng;

    if (targetLat !== null) {
      const ok = confirm("目的地はすでに設定されています。変更しますか?");
      if (!ok) return;
    }

    targetLat = newLat;
    targetLng = newLng;
    arrived = false;

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

    document.getElementById("targetInfo").textContent =
      "目的地を設定しました。(共有中…)";

    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 (selfMarker) map.removeLayer(selfMarker);
  selfMarker = createLabeledMarker(lastLat, lastLng, currentUser, true);
  selfMarker.addTo(map);
}
// ===================================
// メンバー一覧(差分更新でチラつき防止)
// ===================================
function showMemberList(latestByDevice) {
  const list = document.getElementById("memberList");

  // ① 既存の<li>を map に
  const exist = {};
  Array.from(list.children).forEach(li => {
    exist[li.dataset.deviceId] = li;
  });

  // ② 今オンラインの人を処理
  Object.values(latestByDevice).forEach(row => {
    const id = row.device_id;
    const diff = (Date.now() - new Date(row.updated_at)) / 1000;
    const online = diff < 6;

    let li = exist[id];

    if (!li) {
      // 初登場 → 新規作成
      li = document.createElement("li");
      li.dataset.deviceId = id;

      const icon = document.createElement("div");
      icon.className = "member-icon";
      li.appendChild(icon);

      const name = document.createElement("span");
      name.className = "member-name";
      li.appendChild(name);

      const status = document.createElement("span");
      status.className = "status-text";
      li.appendChild(status);

      list.appendChild(li);
    }

    // 色
    const color = id === deviceId ? "#58c16b" : "#FFD700";
    li.querySelector(".member-icon").style.background = color;

    // 名前
    li.querySelector(".member-name").textContent = row.user_name;

    // オンライン・オフライン
    li.classList.toggle("online", online);
    li.classList.toggle("offline", !online);
    li.querySelector(".status-text").textContent =
      online ? "🟢オンライン" : "🔴オフライン";

    // 既存マップから削除(処理済み)
    delete exist[id];
  });

  // ③ 存在しなくなった人だけ削除
  Object.values(exist).forEach(li => li.remove());
}


// ===================================
// 他ユーザー取得
// ===================================
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);

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

// ===================================
// 距離計算
// ===================================
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);

  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 checkArrival() {
  if (targetLat === null) return;

  const d = distanceMeters(lastLat, lastLng, targetLat, targetLng);
  const km = (d / 1000).toFixed(2);
  const box = document.getElementById("targetInfo");

  if (lastShownDistance === null || Math.abs(d - lastShownDistance) > 50) {
    box.textContent = "目的地まで 約 " + km + " km";
    lastShownDistance = d;
  }

  if (d < 120 && !arrived) {
    arrived = true;
    box.textContent = "🎉 目的地に到着しました! 🎉";
    box.style.background = "#ffe4e1";
    box.style.borderLeft = "5px solid #ff4d6d";
    if (navigator.vibrate) navigator.vibrate([200, 100, 200]);
  }
}

// ===================================
// 駅取得
// ===================================
async function fetchStationsAround(lat, lng) {
  const query = `
    [out:json];
    node["railway"="station"](around:5000,${lat},${lng});
    out;
  `;
  const url =
    "https://overpass-api.de/api/interpreter?data=" +
    encodeURIComponent(query);
  const res = await fetch(url);
  const json = await res.json();
  return json.elements || [];
}

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

  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 sLat = st.lat;
      const sLng = st.lon;
      const name = st.tags?.name || "駅名不明";

      const d = distanceMeters(lastLat, lastLng, sLat, sLng);
      if (d < nearestDist) {
        nearest = { name, lat: sLat, lng: sLng };
        nearestDist = d;
      }

      const mk = L.marker([sLat, sLng], { icon: stationIcon }).addTo(map);
      mk.bindPopup(name + "駅");
      stationMarkers.push(mk);
    });

    box.textContent =
      "最寄り駅:" +
      nearest.name +
      "(約 " +
      (nearestDist / 1000).toFixed(2) +
      " km)";
  } catch {
    box.textContent = "駅情報を取得できませんでした。";
  }
}

// ===================================
// 共有目的地の読込
// ===================================
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;
  arrived = false;
  lastShownDistance = null;

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

  document.getElementById("targetInfo").textContent =
    "目的地が共有されました!距離計算中…";
}

// ===================================
// main
// ===================================
async function main() {
  loadParams();
  await decideHost(); // ← 本物のホスト判定!

  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();

  loadStations();
  loadSharedTarget();

  setInterval(async () => {
    try {
      const pos = await getPosition();
      lastLat = pos.latitude;
      lastLng = pos.longitude;

      renderSelfMarker();
      await saveMyLocation(lastLat, lastLng);
      checkArrival();
    } catch {}
  }, 2000);

  setInterval(showOtherUsers, 1000);
  setInterval(loadSharedTarget, 10000); // ← 上書きしない安全な更新

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

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

window.addEventListener("DOMContentLoaded", main);