Search code examples
javascriptajaxhtmlgeolocation

Geolocation permission


I am trying to do a simple geolocation html5 :

$(function() {  
    var currentLatitude ="";
    var currentLongitude ="";
    if (navigator.geolocation) {
        navigator.geolocation.getCurrentPosition(showPosition, showError);
    function showPosition(position) {
            currentLatitude = position.coords.latitude;
            currentLongitude = position.coords.longitude;                                                
        }   
    } else {
       // location based on the IP - less accurate

    }  

And the error is permission for location error even when i had my site(running local) on exceptions . My second option is by IP (ipinfo.io) :

function showError(error) {
      var x = $('#curr_loc_target');

      switch(error.code) {
        case error.PERMISSION_DENIED:
          x.html("User denied the request for Geolocation.");
           jQuery.get("http://ipinfo.io/json", function (response)
               {
                    console.log(response) ;
                   currentLatitude = response.loc.split(',')[0]; 
                   currentLongitude = response.loc.split(',')[1];
                   console.log("lat" + currentLatitude+ "," + "lngs" +currentLongitude) ;
               } );
          break;
        case error.POSITION_UNAVAILABLE:
          x.html("Location information is unavailable.");
          break;
        case error.TIMEOUT:
          x.html("The request to get user location timed out.");
          break;
        case error.UNKNOWN_ERROR:
          x.html("An unknown error occurred.");
          break;
        }
    }

And it works but it is not accurate at all . All i need to do is send lat , lng to my server , if it will be not local it will work ? or anyone knows a way to solve this error ?


Solution

  • The code working on my site. It seems like you have disabled the geolocation tracking on your browser that send you directly to the error scenario. Please take note that it will require user to explicitly grant you the permission to get the location tracking info.