Domanda

I am trying to find user's location meaning in which country he is browsing. I need to use HTML and Javascript for this. I have seen various posts on stackoverflow on this in which people have suggested to use different different API's. I am mostly interested in any free API's and which can give me three letter country code not two. Any other API's is fine with me, it's not mandatory that I need to use IPInfo, I can als use geonames as well.

And after finding the user's country code, I need to make a URL like this, suppose the countryCode is 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 below code with me which will find the currentLocation but the countryCode is of two letter only. I need three letter country code and then make the url accordingly.

<html>
    <head>
        <title>Get web visitor's 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?

È stato utile?

Soluzione

ipinfo.io does NOT provide a three-letter country code. You'll have to manually produce 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.country as the key to find the value from your homemade array.

HTML

<a id="newURL"></a>

Altri suggerimenti

I don't think ipinfo provides a three letter country code.We have to use an array with all the available country code and match with the three letter country code.

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

Hope it help's

Autorizzato sotto: CC-BY-SA insieme a attribuzione
Non affiliato a StackOverflow
scroll top