<script type="application/javascript">
function getip(json){
alert(json.ip); // alerts the ip address
}
</script>
</script>
我可以通过这段代码获取用户的IP地址...
我想要找到这个IP的位置。 我该怎么做?
<script type="application/javascript">
function getip(json){
alert(json.ip); // alerts the ip address
}
</script>
</script>
我可以通过这段代码获取用户的IP地址...
我想要找到这个IP的位置。 我该怎么做?
http://www.geoplugin.net/json.gp?ip=<your ip here>&jsoncallback=<suitable javascript function in your source>
,然后包括返回的源代码并运行您在jsoncallback
中指定的函数以获取地理位置信息。https
而不是http
,此服务需要付费订阅。在https
托管的网站内部使用API中的http
将被浏览器阻止。 - Anubhab Maji这里提供一个运行在MaxMind数据库上的免费开源社区运行的地理位置IP服务: https://ipstack.com/
示例
https://api.ipstack.com/160.39.144.19
限制
每月10,000个查询
使用将IP地址映射到位置的API很容易。运行片段以获取输入框中IP的城市和国家。
$('.send').on('click', function(){
$.getJSON('https://ipapi.co/'+$('.ip').val()+'/json', function(data){
$('.city').text(data.city);
$('.country').text(data.country);
});
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<input class="ip" value="8.8.8.8">
<button class="send">Go</button>
<br><br>
<span class="city"></span>,
<span class="country"></span>
jQuery.get("http://ipinfo.io", function(response) {
console.log(response.city);
}, "jsonp");
如果您无法完成上述代码,这里有一个使用jquery的简单方法:
$.getJSON("http://www.geoplugin.net/json.gp?jsoncallback=?",
function (data) {
for (var i in data) {
document.write('data["i"] = ' + i + '<br/>');
}
}
);
let apiKey = "your_api_key_here";
async function getLocation (ip) {
let url = `https://api.ipgeolocation.io/ipgeo?apiKey=${apiKey}&ip=${ip}`;
await fetch(url).then((response) =>
response.json().then((json) => {
const output = `
---------------------
Country: ${json.country_name}
State: ${json.state_prov}
City: ${json.city}
District: ${json.district}
Lat / Long: (${json.latitude}, ${json.longitude})
---------------------
`;
console.log(output);
})
);
};
getLocation('154.28.188.208') // prints the location
$.get("https://api.ipdata.co?api-key=test", function (response) {
$("#ip").html("IP: " + response.ip);
$("#city").html(response.city + ", " + response.region);
$("#response").html(JSON.stringify(response, null, 4));
}, "jsonp");
<h1><a href="https://ipdata.co">ipdata.co</a> - IP geolocation API</h1>
<div id="ip"></div>
<div id="city"></div>
<pre id="response"></pre>
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
$.getJSON('//freegeoip.net/json/?callback=?', function(data) {
console.log(JSON.stringify(data, null, 2));
});
以下任意一个链接都可以解决这个问题:
http://ipinfodb.com/ip_location_api_json.php
这些链接提供了通过Javascript获取用户位置的教程。但是,它们是通过API连接到外部数据服务来实现的。如果您有一个极高流量的网站,您可能希望自己托管数据(或者使用高级API服务)。要自己托管所有内容,您需要托管一个包含IP地理位置信息的数据库,并使用ajax将用户位置输入Javascript。如果您想采取这种方法,可以在下面获取免费的IP信息数据库:
http://www.ipinfodb.com/ip_database.php
请注意,此方法需要定期更新数据库以确保跟踪IP地址到位置的准确性。