[英]How can I use GMaps API to display a draggable pin that defaults to the user's HTML5 geolocation?
[英]How can I find a user’s country using HTML5 geolocation?
我熟悉HTML5地理位置,用于返回用户位置的粗略坐标。
但是,如何返回其坐标所在国家/地区的名称?
如果你只是想要这个国家,那么使用ws.geonames.org
而不是谷歌这是一个更简单的方法:
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(result.countryName);
});
});
}
通常我会说使用谷歌服务意味着更高的可靠性,但最近有很多谷歌服务退役,看看其他一些解决方案可能是个好主意。
顺便说一句,我使用我能找到的所有免费地理编码服务做了一些实验。 一旦其中一个人找到可接受的结果,它就会返回国家和服务的名称。
随意通过JSFiddle玩它: 通过多个地理定位webapis延迟查找国家代码
var geocoder = new google.maps.Geocoder();
geocoder.geocode({'latLng': <YOURLATLNGRESPONSEFROMGEO>}, function(results, status) {
if (status == google.maps.GeocoderStatus.OK) {
if (results[0]) {
var loc = getCountry(results);
}
}
});
function getCountry(results)
{
for (var i = 0; i < results[0].address_components.length; i++)
{
var shortname = results[0].address_components[i].short_name;
var longname = results[0].address_components[i].long_name;
var type = results[0].address_components[i].types;
if (type.indexOf("country") != -1)
{
if (!isNullOrWhitespace(shortname))
{
return shortname;
}
else
{
return longname;
}
}
}
}
function isNullOrWhitespace(text) {
if (text == null) {
return true;
}
return text.replace(/\s/gi, '').length < 1;
}
这是我用的:)
如果你在地理位置上工作有问题,就像我在Chrome中一样,那么我可以推荐这种替代方式(例如使用jQuery):
$.getJSON("https://freegeoip.net/json/", function(data) {
const countryCode = data.country_code;
const countryName = data.country_name;
const ip = data.ip;
const timezone = data.time_zone;
const latitude = data.latitude;
const longitude = data.longitude;
alert("Country Code: " + countryCode);
alert("Country Name: " + countryName);
alert("IP: " + ip);
alert("Time Zone: " + timezone);
alert("Latitude: " + latitude);
alert("Longitude: " + longitude);
});
注意你需要设置'username'属性来使用这个api,否则你会得到错误。
setTimeout(function() {
if (navigator.geolocation) {
navigator.geolocation.getCurrentPosition(function(position) {
$.getJSON('http://api.geonames.org/countryCode', {
lat : position.coords.latitude,
lng : position.coords.longitude,
type : 'JSON',
username : 'demo'
}, function(result) {
alert(result.countryName);
});
});
}
}, 1000);
类似的答案来自@hippietrail,但另一项服务没有注册。
if ( navigator.geolocation ) {
navigator.geolocation.getCurrentPosition(function(position) {
$.ajax('http://www.datasciencetoolkit.org/coordinates2politics/'
+ position.coords.latitude + ','
+ position.coords.longitude, {dataType: 'jsonp'})
.done(function(data, textStatus, jqXHR) {
if ( textStatus === 'success' ) {
var country = data[0].politics[0].name
alert(country)
}
})
}
您将需要一个反向地理编码器服务。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.