如何使用geonames service api获取国家/地区代码信息,而不是使用html5位置对象

ars*_*nal 1 html javascript jquery geolocation geonames

我正在尝试使用Geonames Servcie API获取用户当前位置的国家/地区代码.我相信geonames service 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>
Run Code Online (Sandbox Code Playgroud)

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

Uncaught ReferenceError: position is not defined

ade*_*neo 6

使用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);
            });
        });
    }
}); 
Run Code Online (Sandbox Code Playgroud)

小提琴

或者您可以使用服务:

$(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);
    });
}); 
Run Code Online (Sandbox Code Playgroud)

小提琴