【问题标题】:navigator.geolocation getCurrentPosition not updating in Chrome Mobilenavigator.geolocation getCurrentPosition 未在 Chrome 移动版中更新
【发布时间】:2012-11-14 20:44:01
【问题描述】:

我创建了一个专为智能手机设计的网站(可通过http://dev.gkr33.com 访问)并尝试使用 navigator.geolocation api 并通过 getCurrentPosition 获取您的位置。这似乎最初有效,但是如果您尝试刷新页面,它总是会带回最后的 GPS 位置。我在页面上添加了一些调试信息,这些信息获取 getCurrentPosition 返回的时间,并且在初始定位后它总是返回相同的时间(精确到毫秒)。

这似乎只发生在 Chrome 移动版中。如果我通过现有的 Android 浏览器浏览该网站,它每次都能正常工作。

代码如下所示;

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

我尝试了各种 maxAge 和 timeout 值,但似乎没有什么会影响相同的 position.coords 和 position.time 值。

我认为 Chrome Mobile 可能存在问题,但我目前不想做太多假设,只是需要澄清一下,我在代码中没有犯类似布偶比例的错误。

非常感谢您提供的任何帮助。

更新:我想我应该说我已经在两台 Android 设备上进行了测试; HTC One X+ 和三星 Galaxy Tab 7.7 结果相同。在两个股票浏览器上都可以正常工作,并且在两个 Chrome 上都不会刷新位置。稍后将在 Apple 设备上进行测试:)

【问题讨论】:

    标签: google-chrome mobile geolocation page-refresh


    【解决方案1】:

    我从来没有深入了解这个问题,但我通过使用watchPosition 调用解决了这个问题,并在清除watchID 之前将其包装在5 秒的等待中。检查下面的代码:

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

    目前我还没有玩过“选项”值或超时延迟,但上面的代码在我尝试过的每个平台上都带回了准确的定位信息。

    希望这可以帮助遇到同样问题的人:)

    【讨论】:

    • 那么,您是否只执行了一次此代码,并且即使在清除手表 ID 后,您仍会在 gotPos 方法中获得更新?或者您是否定期调用此代码以获取新的更新位置?
    【解决方案2】:

    我终于在 android 中找到了适用于 firefox、chrome 和 default navigator 的工作版本(仅限 4.2 测试):

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

    【讨论】:

      【解决方案3】:

      getCurrentLocation() 不再适用于 Chrome 浏览器中的不安全来源。切换到安全原始 (HTTPS) 以启用。

      【讨论】:

        猜你喜欢
        • 2013-04-09
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 2014-11-24
        • 1970-01-01
        • 2014-08-07
        相关资源
        最近更新 更多