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 currentGroup = "";
let currentUser = "";
let map;
let userMarker;
let otherMarkers = [];
let reloadTimer;

// デフォルト位置(皇居あたり)
const DEFAULT_LAT = 35.685175;
const DEFAULT_LNG = 139.752799;

// ===============================
// URL から group / user を取得して表示
// ===============================
function loadParams() {
  const params = new URLSearchParams(location.search);
  currentGroup = params.get("group") || "未指定";
  currentUser = params.get("user") || "名無し";

  const gSpan = document.getElementById("groupName");
  const uSpan = document.getElementById("userName");

  if (gSpan) gSpan.textContent = currentGroup;
  if (uSpan) uSpan.textContent = currentUser;
}

// ===============================
// アイコン定義(自分 / 他人)
// ===============================
const myIcon = L.icon({
  iconUrl: "https://maps.gstatic.com/mapfiles/ms2/micons/blue-dot.png",
  iconSize: [32, 32],
});

const otherIcon = L.icon({
  iconUrl: "https://maps.gstatic.com/mapfiles/ms2/micons/red-dot.png",
  iconSize: [32, 32],
});

// ===============================
// 現在地取得(Promise)
// ===============================
function getPosition() {
  return new Promise((resolve, reject) => {
    if (!navigator.geolocation) {
      reject(new Error("このブラウザは位置情報に対応していません"));
      return;
    }

    navigator.geolocation.getCurrentPosition(
      (pos) => resolve(pos.coords),
      (err) => reject(err),
      { enableHighAccuracy: true }
    );
  });
}

// ===============================
// 地図初期化
// ===============================
function initMap(lat, lng) {
  map = L.map("map").setView([lat, lng], 15);

  L.tileLayer("https://tile.openstreetmap.org/{z}/{x}/{y}.png", {
    maxZoom: 19,
    attribution: "© OpenStreetMap contributors",
  }).addTo(map);

  userMarker = L.marker([lat, lng], { icon: myIcon }).addTo(map);
  userMarker.bindPopup(`あなた(${currentUser})`);
}

// ===============================
// 自分の位置を「1件だけ」残すように保存
// ===============================
async function saveMyLocation(lat, lng) {
  if (!currentGroup || !currentUser) return;

  // 自分の古い記録を削除
  await supa
    .from("locations")
    .delete()
    .eq("group_name", currentGroup)
    .eq("user_name", currentUser);

  // 新しい記録を1件だけ挿入
  await supa.from("locations").insert({
    group_name: currentGroup,
    user_name: currentUser,
    lat: lat,
    lng: lng,
  });
}

// ===============================
// グループ内の他ユーザーの最新位置を読み込み表示
// ===============================
async function showOtherUsers() {
  if (!currentGroup) return;

  // 新しい順に全部取得
  const { data, error } = await supa
    .from("locations")
    .select("*")
    .eq("group_name", currentGroup)
    .order("updated_at", { ascending: false });

  if (error) {
    console.error("位置情報の取得エラー:", error);
    return;
  }

  // 既存マーカー削除(自分のは残す)
  otherMarkers.forEach((m) => map.removeLayer(m));
  otherMarkers = [];

  // ユーザーごとに「最初に出てきた(=最新)」だけ使う
  const usedNames = new Set();

  data.forEach((row) => {
    const name = row.user_name || "名無し";

    // 自分はスキップ(自分の青ピンは別で表示済み)
    if (name === currentUser) return;

    // すでにこのユーザーのピンを作っていたらスキップ
    if (usedNames.has(name)) return;
    usedNames.add(name);

    const mk = L.marker([row.lat, row.lng], { icon: otherIcon }).addTo(map);
    mk.bindPopup(`${name} さん<br>更新: ${row.updated_at}`);
    otherMarkers.push(mk);
  });
}

// ===============================
// メイン処理
// ===============================
async function main() {
  loadParams();

  let lat = DEFAULT_LAT;
  let lng = DEFAULT_LNG;

  try {
    const pos = await getPosition();
    lat = pos.latitude;
    lng = pos.longitude;
  } catch (e) {
    console.warn("現在地取得に失敗。デフォルト位置を表示します。", e);
  }

  initMap(lat, lng);

  try {
    await saveMyLocation(lat, lng);
  } catch (e) {
    console.error("位置情報の保存エラー:", e);
  }

  await showOtherUsers();

  // 10秒ごとに最新位置を反映
  if (reloadTimer) clearInterval(reloadTimer);
  reloadTimer = setInterval(showOtherUsers, 20000);
}

window.addEventListener("DOMContentLoaded", main);