navigator.geolocation.getCurrentPosition sometimes works sometimes doesn't

前端 未结 25 2024
伪装坚强ぢ
伪装坚强ぢ 2020-11-22 13:33

So I have a pretty simple bit of JS using the navigator.geolocation.getCurrentPosition jammy.

$(document).ready(function(){
  $(\"#business-locate, #people-l         


        
25条回答
  •  感动是毒
    2020-11-22 14:08

    In our case it always works the first time but rerunning the function more than 3-4 times, it fails.

    Simple workaround: Store it's value in LocalStorage.

    Before:

    navigator.geolocation.getCurrentPosition((position) => {
      let val = results[0].address_components[2].long_name;
      doSthWithVal(val);      
    }, (error) => { });
    

    After:

    if(localStorage.getItem('getCurrentPosition') !== null) {
      doSthWithVal(localStorage.getItem('getCurrentPosition'));
    }
    else {
      navigator.geolocation.getCurrentPosition((position) => {
          let val = results[0].address_components[2].long_name;
          localStorage.setItem('getCurrentPosition',val);
          doSthWithVal(val);      
      }, (error) => { });
    }
    

提交回复
热议问题