实时检索地理位置 (HTML5)

Retrieve geolocation in real time (HTML5)

我有这个代码:

    var map;
    var geocoder;

    function initialize() {
      var mapOptions = {
        zoom: 18
      };
      map = new google.maps.Map(document.getElementById('map-canvas'),
          mapOptions);

      // Try HTML5 geolocation
      if(navigator.geolocation) {
        navigator.geolocation.getCurrentPosition(function(position) {
          var pos = new google.maps.LatLng(position.coords.latitude,
                                           position.coords.longitude);

          var marker = new google.maps.Marker({
              position: pos,
              map: map,
              title: 'Posizione Attuale'

          });

          map.setCenter(pos);
        }, function() {
          handleNoGeolocation(true);
          alert('GPS DISATTIVATO')
        },
        {enableHighAccuracy: true, timeout: 5000, maximumAge: 0});
      }else {
        // Browser doesn't support Geolocation
        handleNoGeolocation(false);
      }
      geocoder = new google.maps.Geocoder();

    }

我希望当我走在街上时,标记会在地图上实时移动(就像导航仪一样)。 我怎样才能做到这一点?我是 javascript 语言的新手。

setInterval(function, delay)

(function(){
    // do some stuff
    setTimeout(arguments.callee, 60000);
})();

第二个方法保证,在您的代码执行之前不会进行下一次调用。

最终代码将取决于选择的方法。

可能是

var map;
var geocoder;
var delay = 1000;

function initialize() {
  var mapOptions = {
    zoom: 18
  };
  map = new google.maps.Map(document.getElementById('map-canvas'),
      mapOptions);

  // Try HTML5 geolocation
  if(navigator.geolocation) {
    navigator.geolocation.getCurrentPosition(function(position) {
      var pos = new google.maps.LatLng(position.coords.latitude,
                                       position.coords.longitude);

      var marker = new google.maps.Marker({
          position: pos,
          map: map,
          title: 'Posizione Attuale'

      });

      map.setCenter(pos);
    }, function() {
      handleNoGeolocation(true);
      alert('GPS DISATTIVATO')
    },
    {enableHighAccuracy: true, timeout: 5000, maximumAge: 0});
  }else {
    // Browser doesn't support Geolocation
    handleNoGeolocation(false);
  }
  geocoder = new google.maps.Geocoder();

}
setInterval(initialize, delay)