Find a three letter country code using HTML and Javascript

I am trying to find the value of the location of the user in which country he is viewing. For this I need to use HTML and Javascript. I saw various posts on stackoverflow where people suggested using different APIs. What interests me most is any free API, and which can give me three-letter code, not two. Any other API is fine with me, it is not necessary that I need to use IPInfo, I can also use geonames.

And after finding the user’s country code, I need to make such a URL, suppose countryCode is the USA, then it should be like this:

some_url&countryCode=USA

if countryCode is IND, then it should be like this:

some_url&countryCode=IND

I have the code below with me that will find currentLocation, but countryCode has only two letters. I need a country code with three letters, and then enter the URL accordingly.

<html>
    <head>
        <title>Get web visitor location</title>
    <script src="https://ajax.googleapis.com/ajax/libs/jquery/1.8.3/jquery.min.js"></script>

    <script>

    $.get("http://ipinfo.io", function (response) {
    $("#ip").html("IP: " + response.ip);
    $("#address").html("Location: " + response.city + ", " + response.region);
    $("#details").html(JSON.stringify(response, null, 4));
    }, "jsonp");

    </script>

    </head>
    <body>
<hr/>
<div id="ip"></div>
<div id="address"></div>
<hr/>Full response: <pre id="details"></pre>

<a href="url&country=countryCode">url</a>

    </body>
</html>

Can anyone help me with this?

0
source share
2 answers

ipinfo.iocontains NOT a three-letter country code. You will have to manually create an array:

 var threeLtrCC.US = 'USA';
 var threeLtrCC.IN = 'IND';
 ...
 $.get("http://ipinfo.io", function (response) {
     var cc = threeLtrCC[response.country];
     $('#newURL').text('some_url?countryCode=' + cc);
     $('#newURL').attr('href','some_url?countryCode=' + cc);         
     $("#details").html(JSON.stringify(response, null, 4));
 }, "jsonp");

and then use response.countryas a key to search for values ​​from your home array.

HTML

<a id="newURL"></a>
+1
source

I do not think ipinfo contains a country code with three letters. We must use an array with all available country code and match the code with three letters.

http://www.worldatlas.com/aatlas/ctycodes.htm

,

0

Source: https://habr.com/ru/post/1016873/


All Articles