document.addEventListener("DOMContentLoaded", () => {
var mymap = L.map("locationmap").setView([38.891, 139.824], 16);
L.tileLayer('https://{s}.tile.osm.org/{z}/{x}/{y}.png', {
attribution: '© <a href="http://osm.org/copyright">OpenStreetMap</a> contributors'
}).addTo(mymap);
var locmarker = L.marker(mymap.getCenter()).addTo(mymap);
locmarker.bindPopup("STARTを押してね").openPopup();
let watchId = null;
let polyline = L.polyline([], { color: 'blue' }).addTo(mymap);
let totalDistance = 0;
let lastLatLng = null;
function startLogging() {
if (watchId !== null) return;
watchId = navigator.geolocation.watchPosition(
(position) => {
const { latitude, longitude } = position.coords;
const latLng = L.latLng(latitude, longitude);
polyline.addLatLng(latLng);
mymap.setView(latLng, 13);
if (lastLatLng) {
const distance = lastLatLng.distanceTo(latLng);
totalDistance += distance;
document.getElementById("distance").textContent = totalDistance.toFixed(2);
}
lastLatLng = latLng;
},
(error) => {
console.error("Geolocation error:", error);
},
{
enableHighAccuracy: true,
maximumAge: 0,
timeout: 5000
}
);
}
function stopLogging() {
if (watchId !== null) {
navigator.geolocation.clearWatch(watchId);
watchId = null;
}
}
function calculateDistance(latLng1, latLng2) {
const R = 6371000; // 地球の半径(m)
const rad = Math.PI / 180;
const dLat = (latLng2.lat - latLng1.lat) * rad;
const dLng = (latLng2.lng - latLng1.lng) * rad;
const a = Math.sin(dLat / 2) ** 2 +
Math.cos(latLng1.lat * rad) * Math.cos(latLng2.lat * rad) *
Math.sin(dLng / 2) ** 2;
const c = 2 * Math.atan2(Math.sqrt(a), Math.sqrt(1 - a));
return R * c; // 距離(m)
}
mymap.on("click", (e) => {
const latLng = e.latlng;
const distance = lastLatLng ? lastLatLng.distanceTo(latLng).toFixed(2) : "計測しています";
L.marker(latLng)
.addTo(mymap)
.bindPopup(`距離: ${distance} m`)
.openPopup();
});
document.getElementById("start").addEventListener("click", startLogging);
document.getElementById("stop").addEventListener("click", stopLogging);
});