HTML5 Samples

Geolocation APIで現在地を連続的に取得する

<!DOCTYPE html>
<html lang="ja">
  <head>
    <meta charset="utf-8">
    <title>Location API Sample</title>
  </head>
  <body>
    <h1>Location API Sample</h1>
    <div id="message"></div>
    <div>
      <button id="stop">STOP</button>
    </div>
    <script>
      var watch;
      window.onload = function() {
          if (navigator.geolocation) {
              watch = navigator.geolocation.watchPosition(function(position) {
                  document.getElementById('message').innerHTML = 'You are at ' + position.coords.latitude + ', ' + position.coords.longitude + ' now';
              }, function(e) {
                  document.getElementById('message').innerHTML = e.message;
              });
          } else {
              document.getElementById('message').innerHTML = 'Location APIがサポートされていません。';
          }
      };
      document.getElementById('stop').onclick = function() {
          navigator.geolocation.clearWatch(watch);
          document.getElementById('message').innerHTML = 'STOP!!';
      };
    </script>
  </body>
</html>