diff --git a/map4.js b/map4.js
index 734f0d8..7b4eed6 100644
--- a/map4.js
+++ b/map4.js
@@ -36,11 +36,11 @@
let stationMarkers = [];
+// 自分の状態
+let myStatus = localStorage.getItem("myStatus") || "移動中";
// ===================================
// ステータス(移動中 / 遅れます / 寄り道中 / 到着)
// ===================================
-let myStatus = localStorage.getItem("myStatus") || "移動中";
-
async function updateStatus(newStatus) {
myStatus = newStatus;
localStorage.setItem("myStatus", newStatus);
@@ -51,7 +51,7 @@
.eq("group_name", currentGroup)
.eq("device_id", deviceId);
- showOtherUsers(); // メンバーリスト更新
+ showOtherUsers(); // メンバー更新
}
function setupStatusButtons() {
@@ -71,7 +71,6 @@
document.getElementById("groupName").textContent = currentGroup || "";
document.getElementById("userName").textContent = currentUser || "";
}
-
// ===================================
// 現在位置
// ===================================
@@ -86,57 +85,8 @@
}
// ===================================
-// 待ち合わせピン
+// ピンのテンプレ
// ===================================
-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],
-});
-
-// ===================================
-// 地図初期化
-// ===================================
-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) {
- if (!confirm("待ち合わせ場所を置き直しますか?")) 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 =
- "待ち合わせ場所を設定しました!";
- });
-}
-
function createLabeledMarker(lat, lng, name, isSelf) {
const pinUrl = isSelf
? "https://raw.githubusercontent.com/pointhi/leaflet-color-markers/master/img/marker-icon-green.png"
@@ -144,48 +94,27 @@
const html = `
-
-
${name}
-
-

-
-
- `;
+ `;
return L.marker([lat, lng], {
icon: L.divIcon({
html,
className: "",
iconSize: [80, 70],
- iconAnchor: [40, 41], // ピン先端を地面に合わせる
+ iconAnchor: [40, 41],
}),
});
}
@@ -196,9 +125,7 @@
function renderSelfMarker() {
if (!map || lastLat === null || lastLng === null) return;
- if (selfMarker) {
- map.removeLayer(selfMarker);
- }
+ if (selfMarker) map.removeLayer(selfMarker);
selfMarker = createLabeledMarker(
lastLat,
@@ -207,12 +134,11 @@
true,
myStatus
);
-
selfMarker.addTo(map);
}
// ===================================
-// 自分の位置保存
+// 自分の位置を Supabase に保存
// ===================================
async function saveMyLocation(lat, lng) {
await supa
@@ -230,12 +156,63 @@
status: myStatus,
});
}
+// ===================================
+// 待ち合わせピンアイコン
+// ===================================
+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],
+});
+// ===================================
+// 地図初期化
+// ===================================
+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) {
+ if (!confirm("待ち合わせ場所を置き直しますか?")) return;
+ }
+
+ targetLat = newLat;
+ targetLng = newLng;
+
+ // 既存の待ち合わせピンを消す
+ if (targetMarker) map.removeLayer(targetMarker);
+
+ // 新しい待ち合わせピン表示
+ targetMarker = L.marker([targetLat, targetLng], { icon: meetIcon }).addTo(map);
+
+ // 共有データとして Supabase に保存
+ await supa.from("shared_target").upsert({
+ group_name: currentGroup,
+ lat: targetLat,
+ lng: targetLng,
+ });
+
+ document.getElementById("targetInfo").textContent =
+ "待ち合わせ場所を設定しました!";
+ });
+}
// ===================================
// 距離計算
// ===================================
function distanceMeters(lat1, lng1, lat2, lng2) {
- const R = 6371000;
+ const R = 6371000; // 地球の半径(m)
const toRad = (deg) => (deg * Math.PI) / 180;
const dLat = toRad(lat2 - lat1);
@@ -249,7 +226,6 @@
return R * 2 * Math.atan2(Math.sqrt(a), Math.sqrt(1 - a));
}
-
// ===================================
// 待ち合わせ距離表示
// ===================================
@@ -262,64 +238,14 @@
document.getElementById("targetInfo").innerHTML =
`待ち合わせ場所まで 約 ${km} km`;
}
-
-// ===================================
-// 駅検索(Overpass API)
-// ===================================
-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 || [];
+function getStatusColor(s) {
+ return {
+ "移動中": "#4caf50",
+ "遅れます": "#ff9800",
+ "寄り道中": "#2196f3",
+ "到着": "#9c27b0",
+ }[s] || "#ccc";
}
-
-// ===================================
-// 最寄り駅のピン
-// ===================================
-async function loadStations() {
- if (!map || lastLat === null) return;
-
- const box = document.getElementById("nearestBox");
-
- const stations = await fetchStationsAround(lastLat, lastLng);
-
- stationMarkers.forEach((m) => map.removeLayer(m));
- stationMarkers = [];
-
- if (!stations || 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)`;
-}
-
// ===================================
// メンバー一覧
// ===================================
@@ -327,7 +253,7 @@
const list = document.getElementById("memberList");
list.innerHTML = "";
- // ★ ここを修正:allMembers を使わず最新データのみで作る
+ // ★最新データでメンバー配列を作成
const members = Object.values(latestByDevice).map(row => ({
device_id: row.device_id,
user_name: row.user_name,
@@ -368,7 +294,8 @@
`;
- // メンバークリックでその位置へ移動
+
+ // メンバーをタップするとそのメンバーの位置へ移動
li.addEventListener("click", () => {
const r = latestByDevice[member.device_id];
if (!r) return;
@@ -378,19 +305,12 @@
list.appendChild(li);
});
}
-
-function getStatusColor(s) {
- return {
- "移動中": "#4caf50",
- "遅れます": "#ff9800",
- "寄り道中": "#2196f3",
- "到着": "#9c27b0",
- }[s] || "#ccc";
-}
// ===================================
// 他ユーザーのピン表示
// ===================================
async function showOtherUsers() {
+
+ // ---- Supabase から最新位置取得 ----
const { data, error } = await supa
.from("locations")
.select("*")
@@ -402,29 +322,41 @@
return;
}
+ // ---- デバイスごとの最新位置だけ残す ----
latestByDevice = {};
(data || []).forEach((r) => {
if (!latestByDevice[r.device_id]) latestByDevice[r.device_id] = r;
});
+ // ---- ホストの自動交代(位置情報の後に実行)----
await checkHostAuto();
+
+ // ---- メンバー一覧を更新 ----
showMemberList(latestByDevice);
- // 他人のピン描画し直し
+ // ---- 既存の他ユーザーピンを消す ----
otherMarkers.forEach((m) => map.removeLayer(m));
otherMarkers = [];
+ // ---- 他ユーザーのピンを描画し直す ----
Object.values(latestByDevice).forEach((r) => {
- if (r.device_id === deviceId) return;
+ if (r.device_id === deviceId) return; // 自分は除外
- const mk = createLabeledMarker(r.lat, r.lng, r.user_name, false, r.status);
+ const mk = createLabeledMarker(
+ r.lat,
+ r.lng,
+ r.user_name,
+ false,
+ r.status
+ );
+
mk.addTo(map);
otherMarkers.push(mk);
});
+ // ---- 全員到着判定 ----
checkAllArrived();
}
-
// ===================================
// 待ち合わせ到着判定
// ===================================
@@ -436,7 +368,7 @@
const ok = users.every((u) => {
const d = distanceMeters(u.lat, u.lng, targetLat, targetLng);
- return d < 120; // 120m 以内
+ return d < 120; // 指定距離以内
});
if (!ok) return;
@@ -456,37 +388,12 @@
await supa.from("shared_target").delete().eq("group_name", currentGroup);
}
-
-// ===================================
-// 共有待ち合わせ読み込み
-// ===================================
-async function loadSharedTarget() {
- const { data, error } = await supa
- .from("shared_target")
- .select("*")
- .eq("group_name", currentGroup)
- .maybeSingle();
-
- if (error) {
- console.error("shared_target 読み込みエラー:", error);
- return;
- }
- if (!data) 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 =
- "待ち合わせ場所が共有されました!";
-
- showDistanceToTarget();
+function formatTime(t) {
+ const d = new Date(t);
+ return `${String(d.getHours()).padStart(2, "0")}:${String(
+ d.getMinutes()
+ ).padStart(2, "0")}`;
}
-
// ===================================
// チャット読み込み
// ===================================
@@ -504,6 +411,7 @@
return;
}
+ // ---- 表示 HTML を構築 ----
chatList.innerHTML = (data || [])
.map((m) => {
const isMe = m.user_name === currentUser;
@@ -521,16 +429,9 @@
})
.join("");
+ // ---- 下までスクロール ----
chatList.scrollTop = chatList.scrollHeight;
}
-
-function formatTime(t) {
- const d = new Date(t);
- return `${String(d.getHours()).padStart(2, "0")}:${String(
- d.getMinutes()
- ).padStart(2, "0")}`;
-}
-
// ===================================
// チャット送信
// ===================================
@@ -548,7 +449,14 @@
input.value = "";
loadMessages();
}
-
+const chatSend = document.getElementById("chatSend");
+const chatInput = document.getElementById("chatInput");
+if (chatSend && chatInput) {
+ chatSend.onclick = sendMessage;
+ chatInput.addEventListener("keydown", (e) => {
+ if (e.key === "Enter") sendMessage();
+ });
+}
// ===================================
// ホスト自動交代
// ===================================
@@ -563,14 +471,15 @@
currentHostName = group.host_name;
+ // 6秒以内に更新があればオンライン扱い
const onlineUsers = Object.values(latestByDevice).filter(
(u) => (Date.now() - new Date(u.updated_at)) / 1000 < 6
);
const hostOnline = onlineUsers.some((u) => u.user_name === currentHostName);
+ // ホストがオフライン → 最新の人がホストに昇格
if (!hostOnline && onlineUsers.length > 0) {
- // 一番新しい人を新ホストに
const newHost = onlineUsers.sort(
(a, b) => new Date(b.updated_at) - new Date(a.updated_at)
)[0];
@@ -583,9 +492,11 @@
currentHostName = newHost.user_name;
isHost = currentUser === currentHostName;
} else {
+ // ホストは通常通り
isHost = currentUser === currentHostName;
}
+ // UI 更新
const hostLabel = document.getElementById("hostStatus");
if (hostLabel) {
hostLabel.textContent = isHost ? "あなたはホストです" : "一般メンバーです";
@@ -596,7 +507,6 @@
disbandBtn.style.display = isHost ? "inline-block" : "none";
}
}
-
// ===================================
// グループ解散
// ===================================
@@ -613,7 +523,6 @@
location.href = `archive.html?group=${encodeURIComponent(currentGroup)}`;
}
-
// ===================================
// グループ状態監視
// ===================================
@@ -634,38 +543,113 @@
location.href = `archive.html?group=${encodeURIComponent(currentGroup)}`;
}
}
+// ===================================
+// 駅検索(Overpass API)
+// ===================================
+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() {
+ if (!map || lastLat === null) return;
+
+ const box = document.getElementById("nearestBox");
+
+ // ---- 駅データ取得 ----
+ const stations = await fetchStationsAround(lastLat, lastLng);
+
+ // 既存の駅ピンを消す
+ stationMarkers.forEach((m) => map.removeLayer(m));
+ stationMarkers = [];
+
+ if (!stations || 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 main() {
- loadParams();
- setupStatusButtons();
+ loadParams(); // URLパラメータ (group,user)
+ setupStatusButtons(); // ステータスボタン設定
- let lat = 35.681236,
- lng = 139.767125; // 皇居
+ // ---- 初期値は皇居 ----
+ let lat = 35.681236, lng = 139.767125;
+ // ---- 現在位置を取得 ----
try {
const pos = await getPosition();
lat = pos.latitude;
lng = pos.longitude;
} catch {
- // 失敗したら皇居のまま
+ // 位置取得失敗 → 初期値のまま
}
lastLat = lat;
lastLng = lng;
+ // ---- 地図初期化 ----
initMap(lat, lng);
+
+ // ---- 自分のピン描画 & Supabase へ保存 ----
renderSelfMarker();
await saveMyLocation(lat, lng);
+ // ---- 他のユーザーの位置表示 ----
await showOtherUsers();
+
+ // ---- 共有された待ち合わせ場所の取得 ----
loadSharedTarget();
+
+ // ---- チャット読み込み ----
loadMessages();
+
+ // ---- 駅表示 ----
loadStations();
- // ▼ 定期更新
+ // ---------------------------------------
+ // ▼ ▼ ▼ 定期的な更新処理 ▼ ▼ ▼
+ // ---------------------------------------
+
+ // GPS更新 & 自分の位置保存
setInterval(async () => {
try {
const pos = await getPosition();
@@ -678,14 +662,27 @@
} catch {}
}, 2500);
+ // 他ユーザーの位置更新
setInterval(showOtherUsers, 1500);
+
+ // 待ち合わせアイコンの再読込
setInterval(loadSharedTarget, 9000);
+
+ // チャット更新
setInterval(loadMessages, 2500);
+
+ // ホスト自動交代
setInterval(checkHostAuto, 4000);
+
+ // グループ解散監視
setInterval(checkGroupActive, 4000);
+
+ // 駅の再検索
setInterval(loadStations, 15000);
- // ▼ ボタン類
+ // ---------------------------------------
+ // ▼ ▼ ▼ ボタンの設定 ▼ ▼ ▼
+ // ---------------------------------------
const exitBtn = document.getElementById("exitBtn");
if (exitBtn) {
exitBtn.onclick = () => (location.href = "index.html");
@@ -705,10 +702,9 @@
});
}
- // 画面表示後に地図サイズ調整
+ // ---- 地図のサイズを調整(スマホ対応) ----
setTimeout(() => map.invalidateSize(), 500);
}
-
// ===================================
// DOMContentLoaded
// ===================================
@@ -717,6 +713,7 @@
const g = p.get("group");
const u = p.get("user");
+ // ---- グループ情報を確認 ----
const { data, error } = await supa
.from("groups")
.select("*")
@@ -741,20 +738,23 @@
return;
}
+ // ---- グループ情報の反映 ----
currentGroup = g;
currentUser = u;
currentHostName = data.host_name;
isHost = currentHostName === currentUser;
- // 初期ホスト表示
+ // ---- ホスト表示の更新 ----
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();
});