Retrieve geolocation in real time (HTML5)

时间:2015-06-15 15:19:37

标签: javascript html5 google-maps gps geolocation

I have this code:

    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();

    }

I would like that when I walk on the street, the marker moves on the map in real time (like a navigator). How can I do that? I'm novice with the javascript language.

1 个答案:

答案 0 :(得分:3)

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)