2012-11-14 14 views
5

Ho creato un sito (accessibile da http://dev.gkr33.com) progettato per uno smartphone e tenta di utilizzare l'API di navigator.geolocation e prendere la posizione tramite getCurrentPosition. Questo sembra funzionare inizialmente, tuttavia se si tenta di aggiornare la pagina riporta sempre l'ultima posizione GPS. Ho aggiunto alcune informazioni di debug sulla pagina che catturano il tempo del ritorno di getCurrentPosition e dopo il posizionamento iniziale restituisce sempre lo stesso tempo (fino al millisecondo).navigator.geolocation getCurrentPosition non si aggiorna in Chrome Mobile

Questo sembra accadere solo in Chrome Mobile. Se navigo nel sito tramite il browser Android di serie, funziona sempre bene.

Il codice è mostrato di seguito;

<script type="text/javascript"> 
    (function ($) { 
    $(document).ready(function() { 
     var options = { enableHighAccuracy: true, maximumAge: 0, timeout: 60000 }; 
     var position; 

     // empty the current html elements, not strictly necessary but 
     // I'm clutching at straws 
     $('#debug-latlng').empty(); 
     $('#debug-time').empty(); 
     $('#debug-address').empty(); 

     // Let's try and find out where we are 
     if(navigator.geolocation) { 
      navigator.geolocation.getCurrentPosition(gotPos, gotErr, options); 
     } else { 
      gotErr(); 
     } 

     // We've got our position, let's show map and update user 
     function gotPos(position) { 
      var info; 
      info = position.coords.latitude+','+position.coords.longitude; 
      $('#debug-latlng').text(info); 
      $('#debug-time').text(parseTimestamp(position.timestamp)); 

      // the following json call will translate the longitude and 
      // latitude into an address (a wrapper for google's geocode call) 

      $.getJSON('http://dev.gkr33.com/api.php', { req: "getLocationInfo", latlng: $('#debug-latlng').text() }, function(json) { 
       $('#debug-address').text(json['results'][0]['formatted_address']); 
      }); 

      var myLatLng = new google.maps.LatLng(position.coords.latitude, position.coords.longitude); 
      var mapOptions = { 
        zoom: 12, 
        center: myLatLng, 
        mapTypeId: google.maps.MapTypeId.ROADMAP 
      };  
      var map = new google.maps.Map(document.getElementById('map_canvas'), mapOptions); 

      var marker = new google.maps.Marker({ 
       position: myLatLng, 
       title: 'You are here', 
       animation: google.maps.Animation.DROP 
      }); 
      marker.setMap(map); 
     } //gotPos 


     // Trap a GPS error, log it to console and display on site 
     function gotErr(error) { 
      var errors = { 
        1: 'Permission denied', 
        2: 'Position unavailable', 
        3: 'Request timeout' 
       }; 
      console.log("Error: " + errors[error.code]); 
      $('#debug-latlng').text('GPS position not available'); 
     } //gotErr 

     // Make timestamp human readable 
     function parseTimestamp(timestamp) { 
      var d = new Date(timestamp); 
      var day = d.getDate(); 
      var month = d.getMonth() + 1; 
      var year = d.getFullYear(); 
      var hour = d.getHours(); 
      var mins = d.getMinutes(); 
      var secs = d.getSeconds(); 
      var msec = d.getMilliseconds(); 
      return day + "." + month + "." + year + " " + hour + ":" + mins + ":" + secs + "," + msec; 
     } // parseTimestamp  
    });   
}) (jQuery); 
</script> 

ho giocato un po 'con i vari valori per il maximumAge e il timeout, ma nulla sembra influenzare gli stessi position.coords e valori position.time.

Penso che ci possa essere un problema con Chrome Mobile, ma non voglio assumere troppo a questo punto nel tempo e ho solo bisogno di chiarimenti sul fatto che non ho commesso un errore di proporzioni simili a muppet nel mio codice.

Mille grazie per l'aiuto che puoi fornire.

AGGIORNAMENTO: Suppongo che avrei dovuto dire che l'ho provato su due dispositivi Android; HTC One X + e un Samsung Galaxy Tab 7.7 con lo stesso risultato. Su entrambi i browser funziona bene, e su entrambi Chrome non aggiorna la posizione. Più tardi eseguirò un test su un dispositivo Apple :)

risposta

7

Non sono mai arrivato in fondo a questo problema, ma ho risolto il problema utilizzando la chiamata watchPosition e l'ho completata in 5 secondi prima di svuotare lo watchID. Controllare il codice qui sotto:

var options = { enableHighAccuracy: true, maximumAge: 100, timeout: 50000 }; 
if(navigator.geolocation) { 
    var watchID = navigator.geolocation.watchPosition(gotPos, gotErr, options); 
    var timeout = setTimeout(function() { navigator.geolocation.clearWatch(watchID); }, 5000); 
} else { 
    gotErr(); 
} 

non ho giocato un po 'con i valori "Opzioni" o il ritardo di timeout in questo momento, ma il codice di cui sopra riporta informazioni dettagliate sul posizionamento su ogni piattaforma che ho provato.

Spero che questo aiuti qualcuno con lo stesso problema :)

1

ho finalmente trovato una versione funzionante per Firefox, Chrome navigatore & di default in Android (4.2 testato solo):

function getGeoLocation() { 
     var options = null; 
     if (navigator.geolocation) { 
      if (browserChrome) //set this var looking for Chrome un user-agent header 
       options={enableHighAccuracy: false, maximumAge: 15000, timeout: 30000}; 
      else 
       options={maximumAge:Infinity, timeout:0}; 
      navigator.geolocation.getCurrentPosition(getGeoLocationCallback, 
        getGeoLocationErrorCallback, 
        options); 
     } 
    }