Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
383 views
in Technique[技术] by (71.8m points)

navigator.geolocation getCurrentPosition not updating in Chrome Mobile

I have created a site (can be accessed at http://dev.gkr33.com) which is designed for a smartphone and attempts to use the navigator.geolocation api and grab your position via getCurrentPosition. This seems to work initially, however if you try to refresh the page it always brings back the last GPS position. I have added some debug information on the page which grabs the time of the getCurrentPosition return and after the initial positioning it always returns the same time (down to the millisecond).

This only seems to happen in Chrome Mobile. If I browse into the site via the stock Android browser it works fine every time.

The code is shown below;

<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>

I have played around with various values for the maximumAge and timeout, but nothing seems to affect the same position.coords and position.time values.

I think there maybe an issue with Chrome Mobile, but I don't wanna assume too much at this point in time and just need clarification that I haven't made a mistake of muppet-like proportions in my code.

Many thanks for any help you can provide.

UPDATE: I suppose I should have said that I have tested this on two Android devices; HTC One X+ and a Samsung Galaxy Tab 7.7 with the same result. On both the stock browser works fine, and on both Chrome doesn't refresh the position. Will test on an Apple Device later :)

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Answer

0 votes
by (71.8m points)

I never got to the bottom of this issue, but I got a way around the problem by utilising the watchPosition call, and wrapping this in a 5 second wait before clearing the watchID. Check the code below:

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

I haven't played around with the "options" values or the timeout delay at the moment, but the above code brings back accurate positioning info on every platform I've tried.

Hope this helps someone with the same issue :)


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...