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;

const DEFAULT_LAT = 35.681236;
const DEFAULT_LNG = 139.767125;

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

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

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

  setInterval(async () => {
    try {
      const pos = await getPosition();
      lastLat = pos.latitude;
      lastLng = pos.longitude;
      renderSelfMarker();
      await saveMyLocation(lastLat, lastLng);
    } catch {}
  }, 2000); // ← 2秒で自分更新(リアルタイム)

  setInterval(showOtherUsers, 1000); // ← 1秒で他人更新

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

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

window.addEventListener("DOMContentLoaded", main);