0

I'm using the following to get the current location of a user and store the coordinates as a cookie. Everything works just fine.

Now I would like to also get the country and save it as a cookie too... Any ideas on how to do get the country??

function getLocation() {
    if (navigator.geolocation) {
        navigator.geolocation.getCurrentPosition(setGeoCookie, displayError);

    } else {
        alert("Geolocation is not supported by the browser you are currently using. Supported browsers: Chrome 5.0, Firefox 3.5, Internet Explorer 9.0, Opera 10.60, Safari 5.0");
    }
}

function setGeoCookie(position) {
    var cookieName = "lat_lng";
    var now = new Date();
    var time = now.getTime();
    time += 3600 * 5000;
    now.setTime(time);
    var cookie_val = position.coords.latitude + "|" + position.coords.longitude;
    document.cookie = cookieName +"=" + cookie_val + '; path=/';
}

function displayError(error) {
    var errors = {
        1: 'Error',
        2: 'Position unavailable',
        3: 'Request timeout'
    };
    alert("Error: " + errors[error.code]);
}
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>

<button onclick="getLocation()">Click here</button>
Dev
  • 437
  • 6
  • 25
  • 1
    You would have to use some service (like Google's Geocoding api) to determine country based on gps. Or maintain your own database of gps to country data and compare – Patrick Evans Nov 19 '19 at 13:28
  • Thanks for the reply @Patrick Evans... Is there a way to get the country with the same function(`navigator.geolocation`) and without using the Google's Geocoding api or other??? – Dev Nov 19 '19 at 14:11
  • No, that information isn't sent as a "country" is a political construct not a positioning one. The GPS satellites would have to be updated every time a country rose,fell,divided, etc. if that were the case – Patrick Evans Nov 19 '19 at 14:37

0 Answers0