您可以为此使用https://ipinfo.io API(这是我的服务)。每天最多 1,000 个请求是免费的(有或没有 SSL 支持)。它为您提供坐标、名称等。这是一个例子:
curl ipinfo.io
{
"ip": "172.56.39.47",
"hostname": "No Hostname",
"city": "Oakland",
"region": "California",
"country": "US",
"loc": "37.7350,-122.2088",
"org": "AS21928 T-Mobile USA, Inc.",
"postal": "94621"
}
这是一个示例,它使用与您从getCurrentPosition() 获得的内容相匹配的 API 响应构造一个 coords 对象:
$.getJSON('https://ipinfo.io/geo', function(response) {
var loc = response.loc.split(',');
var coords = {
latitude: loc[0],
longitude: loc[1]
};
});
这里有一个详细的示例,展示了如何将其用作getCurrentPosition() 的后备:
function do_something(coords) {
// Do something with the coords here
}
navigator.geolocation.getCurrentPosition(function(position) {
do_something(position.coords);
},
function(failure) {
$.getJSON('https://ipinfo.io/geo', function(response) {
var loc = response.loc.split(',');
var coords = {
latitude: loc[0],
longitude: loc[1]
};
do_something(coords);
});
};
});
更多详情请见http://ipinfo.io/developers/replacing-navigator-geolocation-getcurrentposition。