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 map;
let selfMarker = null;
let otherMarkers = [];
let latestByDevice = {};
let lastLat = null;
let lastLng = null;

// 駅マーカー用
let stationMarkers = [];

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],
  shadowSize: [41, 41],
  shadowAnchor: [13, 41],
});

// ===================================
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 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 iconHtml = `
    <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: iconHtml,
      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);
}

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

  selfMarker.on("click", (e) => {
    map.panTo(e.latlng, { animate: true, duration: 0.4 });
  });
}

// ===================================
// メンバー一覧
// ===================================
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;
    const isOnline = diff < 6; // 6秒以内ならオンライン

    li.classList.add(isOnline ? "online" : "offline");

    // 自分=緑 / 他人=黄
    const circleColor = row.device_id === deviceId ? "#58c16b" : "#FFD700";

    const icon = document.createElement("div");
    icon.className = "member-icon";
    icon.style.background = circleColor;

    const name = document.createElement("span");
    name.textContent = row.user_name;

    const status = document.createElement("span");
    status.className = "status-text";
    status.textContent = isOnline ? "🟢オンライン" : "🔴オフライン";

    li.append(icon, name, status);

    li.onclick = () => {
      const marker =
        row.device_id === deviceId
          ? selfMarker
          : otherMarkers.find((m) => m._deviceId === row.device_id);

      if (marker) {
        map.panTo(marker.getLatLng(), { animate: true, duration: 0.5 });
      }
    };

    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)) {
    for (const r of data) {
      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._deviceId = row.device_id;

    mk.on("click", (e) => {
      map.panTo(e.latlng, { animate: true, duration: 0.4 });
    });

    mk.addTo(map);
    otherMarkers.push(mk);
  });
}

// ===================================
// ここから駅関連
// ===================================

// 距離計算(メートル)
function distanceMeters(lat1, lng1, lat2, lng2) {
  const R = 6371000;
  const toRad = (d) => (d * Math.PI) / 180;
  const dLat = toRad(lat2 - lat1);
  const dLng = toRad(lng2 - lng1);
  const a =
    Math.sin(dLat / 2) * Math.sin(dLat / 2) +
    Math.cos(toRad(lat1)) *
      Math.cos(toRad(lat2)) *
      Math.sin(dLng / 2) *
      Math.sin(dLng / 2);
  const c = 2 * Math.atan2(Math.sqrt(a), Math.sqrt(1 - a));
  return R * c;
}

// Overpass API で半径5kmの駅を取得
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);
  if (!res.ok) throw new Error("Overpass API error");
  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 = "5km以内に駅が見つかりませんでした。";
      return;
    }

    let nearest = null;
    let nearestDist = Infinity;

    stations.forEach((st) => {
      const sLat = st.lat;
      const sLng = st.lon;
      const name =
        (st.tags && (st.tags.name || st.tags["name:ja"])) || "駅名不明";

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

      // 駅マーカー追加
      const mk = L.marker([sLat, sLng], { icon: stationIcon }).addTo(map);
      mk.bindPopup(`${name}駅`);
      stationMarkers.push(mk);
    });

    if (nearest) {
      const distKm = (nearestDist / 1000).toFixed(2);
      box.textContent = `ここから一番近いのは「${nearest.name}駅」です!(約 ${distKm}km)`;
    } else {
      box.textContent = "5km以内に駅が見つかりませんでした。";
    }
  } catch (e) {
    console.error(e);
    box.textContent = "駅情報を取得できませんでした。";
  }
}

// ===================================
async function main() {
  loadParams();

  let lat = DEFAULT_LAT,
    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();

  // ★ 駅読み込み(最初の位置で1回だけ)
  loadStations();

  // 自分の位置更新(2秒ごと)
  setInterval(async () => {
    try {
      const pos = await getPosition();
      lastLat = pos.latitude;
      lastLng = pos.longitude;
      renderSelfMarker();
      await saveMyLocation(lastLat, lastLng);
      // 位置が大きく変わったときだけ駅再取得してもよいが、
      // API負荷を考えて今回は初回のみ。
    } catch {}
  }, 2000);

  // 他ユーザー位置更新(1秒ごと)
  setInterval(showOtherUsers, 1000);

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

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

window.addEventListener("DOMContentLoaded", main);