【问题标题】:Find the three letter country code using HTML and Javascript使用 HTML 和 Javascript 查找三个字母的国家/地区代码
【发布时间】:2013-08-04 11:02:49
【问题描述】:

我正在尝试查找用户在哪个国家/地区浏览的位置含义。我需要为此使用 HTML 和 Javascript。我在 stackoverflow 上看到过各种帖子,其中人们建议使用不同的 API。我最感兴趣的是任何免费的 API,它可以给我三个字母的国家代码而不是两个。任何其他 API 对我来说都可以,我不需要使用 IPInfo,我也可以使用地理名称。

并且在找到用户的国家代码后,我需要做一个这样的URL,假设countryCode是USA,那么应该是这样的-

some_url&countryCode=USA

如果 countryCode 是 IND,那么应该是这样的-

some_url&countryCode=IND

我有下面的代码,可以找到 currentLocation,但 countryCode 只有两个字母。我需要三个字母的国家代码,然后相应地制作网址。

<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>

谁能帮我解决这个问题?

【问题讨论】:

  • 我也可以使用其他免费的 API。地名呢?
  • 我还没有解决这个问题。谁能帮帮我?

标签: javascript html ajax geolocation reverse-geocoding


【解决方案1】:

ipinfo.io提供三个字母的国家/地区代码。您必须手动生成一个数组:

 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");

然后使用response.country 作为键从你的自制数组中查找值。

HTML

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

【讨论】:

  • 我试过上面的代码,它不工作。能否提供一个 JSFiddle 示例?
  • 如果与 IPInfo 相比,geonmaes 工作得更好,那么这个例子对我也有很大帮助。
  • 您不能使用跨域 AJAX 调用来制作 jsFiddle。如果您只是将我的代码与来自ipinfo.io 站点的文档一起查看,我相信您会将它们放在一起。
  • 不知何故,我无法把它放在一起。我面临很多问题。我也在尝试使用地名。但没有运气。他们中的任何一个都适合我。
【解决方案2】:

我认为 ipinfo 不提供三字母国家代码。我们必须使用包含所有可用国家代码的数组并与三字母国家代码匹配。

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

希望对你有帮助

【讨论】:

  • 其他 API 呢?
猜你喜欢
  • 1970-01-01
  • 2021-06-13
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2021-02-18
  • 2012-05-10
  • 2019-06-24
  • 1970-01-01
相关资源
最近更新 更多