简体   繁体   中英

How to get country code information using geonames service api not the html5 location object thing

I am trying to get the country code of the user's current location using Geonames Servcie API. And I believe geonames service API will return me two letter country code instead of three letter country code and I need three letter country code. So for this, I have made the mapping between two letter country code and three letter country code.

Below is my code, and some how, my alert box is not working at all. I am pretty much sure I am missing something?

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

What wrong I am doing in my above code? Below is the error I am getting on the console.

Uncaught ReferenceError: position is not defined

Using HTML5 Geolocation you could do :

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

Or you could use a service:

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM