Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

like image 518
troozers Avatar asked Nov 14 '12 20:11

troozers


People also ask

Does geolocation work on mobile?

Geolocation uses mobile devices built-in GPS to accurately show where the device, and the user of the device, are located. This data is accessed through apps that the user grants permission to use their location data.

Why is geolocation not working?

If you are facing problems with geolocation on your website running our WordPress Directory theme using Google Chrome browser, it's because of Google's decision to allow geolocation functionality only for websites that use SSL certificates.

What is navigator geolocation getCurrentPosition?

Description. The getCurrentPosition method retrieves the current geographic location of the device. The location is expressed as a set of geographic coordinates together with information about heading and speed. The location information is returned in a Position object.


3 Answers

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

like image 94
troozers Avatar answered Oct 16 '22 19:10

troozers


I finally found a working version for firefox, chrome & default navigator in android (4.2 tested only):

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);
        }
    }
like image 25
surfealokesea Avatar answered Oct 16 '22 19:10

surfealokesea


getCurrentLocation() no longer works on insecure origins in Chrome browsers. Switch to a secure original (HTTPS) to enable.

like image 45
Kelly Orr Avatar answered Oct 16 '22 19:10

Kelly Orr