最新消息:雨落星辰是一个专注网站SEO优化、网站SEO诊断、搜索引擎研究、网络营销推广、网站策划运营及站长类的自媒体原创博客

javascript - geolocation.watchPosition breaks geolocation.getCurrentPosition - Stack Overflow

programmeradmin4浏览0评论

I'm working on a web app with google maps and using getCurrentPosition() to get the user position. That works fine but I need to track user position over time.

For this I intended to use watchPosition(). Acording to the API reference API reference it must immediatly execute data acquisition and execute the callback, but it doesn't. Instead it freezes, and I can no longer use getCurrentPosition(). I have been searching for a cause for this and I cant figure out why is behaving that way. I'm using the latest Chrome for Linux Mint "Lisa".

I'm working on a web app with google maps and using getCurrentPosition() to get the user position. That works fine but I need to track user position over time.

For this I intended to use watchPosition(). Acording to the API reference API reference it must immediatly execute data acquisition and execute the callback, but it doesn't. Instead it freezes, and I can no longer use getCurrentPosition(). I have been searching for a cause for this and I cant figure out why is behaving that way. I'm using the latest Chrome for Linux Mint "Lisa".

Share Improve this question edited Jan 5, 2012 at 22:04 ThinkingStiff 65.4k30 gold badges147 silver badges241 bronze badges asked Jan 3, 2012 at 23:53 Juan Antonio OrozcoJuan Antonio Orozco 7509 silver badges33 bronze badges
Add a ment  | 

1 Answer 1

Reset to default 15

On a mobile device, .getCurrentPosition() is very inaccurate. Using .watchPosition() is more accurate, but it takes about five seconds to get the best reading. After that, it wastes battery to keep it active.

This checks the position every 15 seconds using .watchPosition() and stops checking after five seconds using .clearWatch().

Demo: https://jsfiddle/ThinkingStiff/phabq6r3/

Script:

var latitude, longitude, accuracy;

function setGeolocation() {
    var geolocation = window.navigator.geolocation.watchPosition( 
        function ( position ) {
            latitude = position.coords.latitude;
            longitude = position.coords.longitude;
            accuracy = position.coords.accuracy;
            document.getElementById( 'result' ).innerHTML += 
                  'lat: ' + latitude + ', '
                + 'lng: ' + longitude + ', '
                + 'accuracy: ' + accuracy + '<br />';
        },
        function () { /*error*/ }, {
            maximumAge: 250, 
            enableHighAccuracy: true
        } 
    );

    window.setTimeout( function () {
            window.navigator.geolocation.clearWatch( geolocation ) 
        }, 
        5000 //stop checking after 5 seconds
    );
};

setGeolocation();

window.setInterval( function () {
        setGeolocation();
    }, 
    15000 //check every 15 seconds
);

HTML:

<div id="result"></div>
发布评论

评论列表(0)

  1. 暂无评论