navigator.geolocation.getCurrentPosition sometimes works sometimes doesn't

前端 未结 25 1680
伪装坚强ぢ
伪装坚强ぢ 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

    The second parameter passed to Geolocation.getCurrentPosition() is the function you want to handle any geolocation errors. The error handler function itself receives a PositionError object with details about why the geolocation attempt failed. I recommend outputting the error to the console if you have any issues:

    var positionOptions = { timeout: 10000 };
    navigator.geolocation.getCurrentPosition(updateLocation, errorHandler, positionOptions);
    function updateLocation(position) {
      // The geolocation succeeded, and the position is available
    }
    function errorHandler(positionError) {
      if (window.console) {
        console.log(positionError);
      }
    }
    

    Doing this in my code revealed the message "Network location provider at 'https://www.googleapis.com/' : Returned error code 400". Turns out Google Chrome uses the Google APIs to get a location on devices that don't have GPS built in (for example, most desktop computers). Google returns an approximate latitude/longitude based on the user's IP address. However, in developer builds of Chrome (such as Chromium on Ubuntu) there is no API access key included in the browser build. This causes the API request to fail silently. See Chromium Issue 179686: Geolocation giving 403 error for details.

    0 讨论(0)
  • 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) => { });
    }
    
    0 讨论(0)
  • 2020-11-22 14:10

    You don't get an error message because it has no timeout by default (At least i think). I have had the same problem with firefox only for me firefox always gives an timeout. You can set a timeout yourself like this.

    My function works great in chrome but i get a timeout everytime in firefox.

        navigator.geolocation.getCurrentPosition(
            function(position) {
                //do succes handling
            },
            function errorCallback(error) {
                //do error handling
            },
            {
                timeout:5000
            }
        );
    

    I recommend to watch your errors carefully. Be expected for everything. Have a backup plan for everything. I use some default values or values from my database myself in case both google geolocations and navigator geolocations fails.

    0 讨论(0)
  • 2020-11-22 14:10

    I'll post this here in case it's useful to anyone…

    On iOS Safari, calls to navigator.geolocation.getCurrentPosition would timeout if I had an active navigator.geolocation.watchPosition function running.

    Starting and stopping the watchPosition properly using clearWatch() as described here, worked: https://developer.mozilla.org/en-US/docs/Web/API/Geolocation/watchPosition

    0 讨论(0)
  • 2020-11-22 14:11

    This is already an old question, but all answers didn't solve my problem, so let's add the one I finally found. It smells like a hack (and it is one), but works always in my situation. Hope in your situation too.

    //Dummy one, which will result in a working next statement.
    navigator.geolocation.getCurrentPosition(function () {}, function () {}, {});
    //The working next statement.
    navigator.geolocation.getCurrentPosition(function (position) {
        //Your code here
    }, function (e) {
        //Your error handling here
    }, {
        enableHighAccuracy: true
    });
    
    0 讨论(0)
  • 2020-11-22 14:12

    May be it helps some one, On Android i had same issue but i figured it out by using setTimeout inside document.ready so it worked for me secondly you have to increase the timeout just incase if user allow his location after few seconds, so i kept it to 60000 mili seconds (1 minute) allowing my success function to call if user click on allow button within 1 minute.

    0 讨论(0)
提交回复
热议问题