Search code examples
javascriptgeolocationgps

GPS location is fetched after second click not on first click


I want to fetch live gps location using javscript to store it in database. I already have implemented it. when user clicks on button. But it fetches location on second click.

Html code

<form action="user_location" method="post" id="form-{{$user->id}}">
    @csrf
    <input type="hidden" name="id" value="{{$user->id}}">
    <input type="hidden" name="location" id="location-{{$user->id}}">
</form>
<a onclick="getLocation({{$user->id}})" class="btn">{{__('Get Location')}}</a>

Javscript code

function getLocation(user_id) {
        if (navigator.geolocation) {
            navigator.geolocation.getCurrentPosition(showPosition);
            
        } else { 
            geolocation = "Geolocation is not supported by this browser.";
        }
        
        if(setlocation){
            form = document.getElementById("form-"+user_id);
            var b = document.getElementById("location-"+user_id)
            b.value = x.textContent;
            form.submit();
        }
    }

    function showPosition(position) {
        x.innerText = position.coords.latitude + "-" + position.coords.longitude;
        setlocation = true;
    }

Solution

  • The getCurrentPosition function is asynchronous. That means that when it is called, it will allow the code after it to run before finishing. So that means that setLocation will not be true whenever your code reaches the following if statement:

    if(setlocation){ // setlocation is still false
    

    Handle your results of getting the position inside the success callback of getCurrentPosition.

    function getLocation(user_id) {
      if (!navigator.geolocation) {
        return;
      }
    
      const form = document.getElementById("form-" + user_id);
      const location = document.getElementById("location-" + user_id);
    
      navigator.geolocation.getCurrentPosition(function(position) {   
        const { coords } = position; 
        location.value = coords.latitude + "-" + coords.longitude;
        form.submit();
      });
    }