[英]How to get country code information using geonames service api not the html5 location object thing
我正在嘗試使用Geonames Servcie API獲取用戶當前位置的國家/地區代碼。 而且我相信地名服務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>
我上面的代碼在做什么錯? 以下是我在控制台上遇到的錯誤。
Uncaught ReferenceError: position is not defined
使用HTML5地理位置,您可以:
$(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);
});
});
}
});
或者您可以使用一項服務:
$(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);
});
});
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.