Newer
Older
reroad-test / 2020-skippage / map.js
@ryusei ryusei on 7 Aug 2020 1 KB edit files
var icon = L.icon({
    iconUrl: 'mashiro_touka.PNG',
    iconSize: [120, 120],
    iconAnchor: [65, 25]
});
var gpsmarker = L.marker(mymap.getCenter(),{icon:icon}).addTo(mymap);
gpsmarker.bindPopup("現在地を探してるよ!!").openPopup();
var destination = L.latLng(38.893344, 139.819209);
var maxTrial = 100
var watchId = null;
var link = document.getElementById("link")

function tryWatchGPS() {
  if (watchId) {
    clearWatch(watchId);
    watchId = null;
  }
  watchId = navigator.geolocation.watchPosition(
    onSuccess, onError, {
      maximumAge: 0,
      timeout: 2000,
      enableHighAccuracy: true
    });
}

function onSuccess(pos) {
  var now_position = L.latLng([pos.coords.latitude, pos.coords.longitude]);
  mymap.panTo(now_position);
  let d = now_position.distanceTo(destination)
  d = Math.round(d*100)/100
  if (d <= 200.00) {
    gpsmarker.setPopupContent(
      "目的地に到着!!"
    ).openPopup().setLatLng(now_position);
    link.innerHTML = '<a href="https://www.yatex.org/gitbucket/SKIP/reroad-test/pages/2020-skippage/yousan.html">クイズに挑戦!!</a>';
  } else {
    gpsmarker.setPopupContent(
      "目的地まであと"+d+"m"
    ).openPopup().setLatLng(now_position);
  }
}

function onError(err) {
  restN = "あと" + (--maxTrial) + "回試行します。";
  gpsmarker.setPopupContent("捕捉失敗:" + restN).openPopup();
  if (maxTrial <= 0) {
    navigator.geolocation.clearWatch(watchId);
  }
}
document.getElementById("start").addEventListener("click", function(e){
    alert("GPS Go!");
    tryWatchGPS();
});