Search code examples
javascripthtmlgoogle-mapsgpsgeolocation

Retrieve geolocation in real time (HTML5)


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.


Solution

  • setInterval(function, delay)
    

    or

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

    The second aproach guarantees, that the next call is not made before your code was executed.

    The final code will depends on the choosen aproach.

    could be

    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)