Newer
Older
2025-shino / loc-chase2.js
document.addEventListener("DOMContentLoaded", () => {

  const mapDiv = document.getElementById("locationmap");

  var mymap = L.map(mapDiv).setView([38.891, 139.824], 16);

  L.tileLayer("https://{s}.tile.osm.org/{z}/{x}/{y}.png", {
    attribution:
      '&copy; <a href="http://osm.org/copyright">OpenStreetMap</a> contributors'
  }).addTo(mymap);

  var locmarker = L.marker(mymap.getCenter()).addTo(mymap);
  locmarker.bindPopup("STARTおしてね").openPopup();

  var watchId = null;

  function stopLOC() {
    if (watchId != null) {
      navigator.geolocation.clearWatch(watchId);
      document.getElementById("title").textContent = "stop";
      locmarker.setPopupContent("停めました");
    }
    watchId = null;
  }

  function tryWatchLOC() {
    stopLOC();
    watchId = navigator.geolocation.watchPosition(
      onSuccess,
      onError,
      { enableHighAccuracy: true }
    );
    document.getElementById("title").textContent = "START!!";
  }

  function updateLocation(latlng) {
    mymap.panTo(latlng);

    const goalLat = 38.892;
    const goalLng = 139.825;

    const dLat = Math.abs(latlng.lat - goalLat);
    const dLng = Math.abs(latlng.lng - goalLng);

    let message;
    if (dLat < 0.0003 && dLng < 0.0003) {
      message = "🎉 GOAL!! 宝を見つけました!";
    } else if (dLat < 0.001 && dLng < 0.001) {
      message = "おしい!もう少し!";
    } else {
      message = "探索中…";
    }

    locmarker
      .setLatLng(latlng)
      .setPopupContent(message)
      .openPopup();
  }

  function onSuccess(pos) {
    const latlng = L.latLng(
      pos.coords.latitude,
      pos.coords.longitude
    );
    updateLocation(latlng);
  }

  function onError() {}

  mapDiv.addEventListener("mousedown", (e) => {
    stopLOC();
    const latlng = mymap.mouseEventToLatLng(e);
    updateLocation(latlng);
  });

  mapDiv.addEventListener("touchstart", (e) => {
    stopLOC();
    const touch = e.touches[0];
    const latlng = mymap.mouseEventToLatLng(touch);
    updateLocation(latlng);
  });


  document.getElementById("start")
    .addEventListener("click", tryWatchLOC);

  document.getElementById("stop")
    .addEventListener("click", stopLOC);

});