简体   繁体   中英

get offline GPS coordinates on android device

Firstly, I'm not a developer or programmer so any help here would be really appreciated! I have a form for use on android mobile devices which launches in Google Chrome. The users can use this form when offline and I was wondering how best to get offline GPS co-ordinates in lat and long. I've been doing some digging around and the code below seems to work. I pull the lat, long and accuracy result from this code into a separate field on my form. What I am not sure about is how to pull in a timestamp so that I can be assured the reading is current and not something cached on the device. The currency and reliability of the coordinates is very important to me.

Any help at all on this would be marvellous!! Thanks, Angela

    <!DOCTYPE html>
    <html>
    <body>

    <p>Get your latitude and longitude (test this to ensure it works when   out of coverage)</p>

    <button onclick="getLocation()">Get your coordinates</button>

    <p id="demo"></p>

    <script>
    var x = document.getElementById("demo");

    function getLocation() {
    if (navigator.geolocation) {
    navigator.geolocation.getCurrentPosition(showPosition);
    } else { 
    x.innerHTML = "Geolocation is not supported by this browser.";
    }
    }

    function showPosition(position) {
    x.innerHTML = "Latitude: " + position.coords.latitude + 
   "<br>Longitude: " + position.coords.longitude;
   "<br>Accuracy: " + position.coords.accuracy              + '<br />'
   }


   function showPosition(position) {
   var latlon = position.coords.latitude + "," + position.coords.longitude   +", Accuracy " + position.coords.accuracy;

   $('input[name="coords"]').val(latlon).trigger('input');
   }


   </script>

  </body>
  </html>

getCurrentPosition accepts a second parameter, PositionOptions . There are a few options you can experiment with to achieve desired results, but specifically you'll want to use maximumAge and enableHighAccuracy . To ensure uncached results:

navigator.geolocation.getCurrentPosition(function(pos){
     console.log('Got position', pos);
}, {
     // can be `0` = uncached, any number in milliseconds,
     // or `Infinity` which will only retrieve cached results
     maximumAge: 0,
     // may take longer, but browser will do everything possible
     // to get the most accurate position
     enableHighAccuracy: true
});

It's also worth noting the returned Position comes with an accuracy property, which returns a positive double indicating the accuracy of your lat and long in meters. Depending on the use case, you may want to require a certain accuracy threshold for users to interact with your app. You can see the full spec here .

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM