javascript - 如何使用 geonames 服务 api 获取国家代码信息而不是 html5 位置对象

标签 javascript jquery html geolocation geonames

我正在尝试使用 Geonames Servcie API 获取用户当前位置的国家/地区代码。而且我相信 geonames 服务 API 会返回两个字母的国家代码而不是三个字母的国家代码,我需要三个字母的国家代码。所以为此,我做了两个字母国家代码和三个字母国家代码之间的映射。

下面是我的代码,不知为何,我的警告框根本不起作用。我很确定我错过了什么?

<html>
    <head>
        <title>Visitor's location</title>

    <script src="https://ajax.googleapis.com/ajax/libs/jquery/1.8.3/jquery.min.js"></script>
    <script>

    $(document).ready( function() {
        $.getJSON('http://ws.geonames.org/countryCode', {
            lat: position.coords.latitude,
            lng: position.coords.longitude,
            type: 'JSON'
        }, function(result) {
            alert('Country: ' + result.countryName + '\n' + 'Code: ' + result.countryCode);
        $('#newURL').attr('href','https://www.google.com&jobid='+result.countryCode);
        });
}); 


    </script>   
    </head>
    <body>

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

    </body>
</html>

我在上面的代码中做错了什么?以下是我在控制台上遇到的错误。

未捕获的 ReferenceError:位置未定义

最佳答案

使用 HTML5 Geolocation 你可以:

$(document).ready( function() {
    if (navigator.geolocation) {
        navigator.geolocation.getCurrentPosition(function(position) {
            $.getJSON('http://ws.geonames.org/countryCode', {
                lat: position.coords.latitude,
                lng: position.coords.longitude,
                type: 'JSON'
            }, function(result) {
                alert('Country: ' + result.countryName + '\n' + 'Code: ' + result.countryCode);
                $('#newURL').attr('href','https://www.google.com&jobid='+result.countryCode);
            });
        });
    }
}); 

FIDDLE

或者您可以使用服务:

$(document).ready( function() {
    $.getJSON("http://freegeoip.net/json/", function(result){
        alert('Country: ' + result.country_name + '\n' + 'Code: ' + result.country_code);
        $('#newURL').attr('href','https://www.google.com&jobid='+result.country_code);
    });
}); 

FIDDLE

关于javascript - 如何使用 geonames 服务 api 获取国家代码信息而不是 html5 位置对象,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/18036690/

相关文章:

javascript - 如何重新创建此背景淡入/弹出效果图标按钮?

javascript - 如何让 service worker 只在第一次访问时注册?

javascript - Angular2 - 我怎么知道在 Angular2 应用程序中选择了哪个单选按钮

javascript - jQuery 如果元素 id 存在,则将类添加到同一元素

javascript - 更改表格行的颜色 onclick 并更改回 onclick

javascript - 无法取消订阅实时更新 : Uncaught Error in onSnapshot: Error: Missing or insufficient permissions

javascript - 延迟加载 "responsive"图片(未知高度)

javascript - 如何从一个指定的子元素中获取 innerHTML

javascript - 通过 php/html/javascript 等控制浏览器的搜索栏文本

php - 从 php html 中的 sql 结果填充下拉列表中获取选定的值