Javascript GeoLocation Caching

眉间皱痕 提交于 2019-12-11 12:08:26

问题


I'm using the following to successfully capture user's location (mobile browser):

<script>
if ( navigator.geolocation ) {
navigator.geolocation.getCurrentPosition(handlePosition);
}
function handlePosition(pos) {
    //this passes lat/long to additional code
 }
</script>

This works, but often times the browser will seemingly cache the location data. The page that calls this geolocation code shows information relative to the user's location, so what happens is the user can move (change location), the page is reloaded, but the previous location data is used (showing incorrect data). Sometimes the page will have to be refreshed once or even twice for the page to use new location data.

Does anyone know of any means to force the code to get and use "up to date" location data each time script is executed?

FWIW, I'm experiencing problem in iOS Safari (6.1). Have not been able to test in Android yet.

Thanks for reading and for any help.


回答1:


No can't be done. You don't have any control over the browser geolocation other than the code in your example. The html5 geo location api is very, very limited and that is a pain. I also had a question whether I could ask it if permission for the domain had already been granted and the answer was also no.

The problem is that the api is implemented in the browser itself and that are just no endpoints for these kind of functions.

What you could do is make an array in js to store previous locations and before you update your view test against that array to see if you got a stale location.




回答2:


You do have this ability now. getCurrentPosition takes three parameters: success, failure and options

Try this:

<script>
if ( navigator.geolocation ) {
navigator.geolocation.getCurrentPosition(handlePosition, (error)=>{}, {maximumAge:0});
}
function handlePosition(pos) {
    //this passes lat/long to additional code
 }
</script>


来源:https://stackoverflow.com/questions/14814256/javascript-geolocation-caching

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!