可以将文章内容翻译成中文,广告屏蔽插件可能会导致该功能失效(如失效,请关闭广告屏蔽插件后再试):
问题:
This question already has an answer here:
-
Get visitors language & country code with javascript (client-side) [duplicate]
3 answers
I\'m trying to extend the native geolocation function
if(navigator.geolocation) {
navigator.geolocation.getCurrentPosition(function(position) {
var latitude = position.coords.latitude;
var longitude = position.coords.longitude;
});
}
so that I can use the visitor\'s country name (perhaps return an informative array).
So far all I\'ve been able to find are functions that display a google maps interface but none actually gave what I want, except for this library which worked well in this example but for some reason didn\'t work on my computer. I\'m not sure why that went wrong there.
Anyways, do you know how I can simply return an array containing information like country, city, etc. from latitude and longitude values?
回答1:
You don\'t need to locate the user if you only need their country. You can look their IP address up in any IP-to-location service (like maxmind). This will be accurate most of the time.
If you really need to get their location, you can get their lat/lng with that method, then query Google\'s or Yahoo\'s reverse geocoding service.
回答2:
You can use my service, http://ipinfo.io, for this. It will give you the client IP, hostname, geolocation information (city, region, country, area code, zip code etc) and network owner. Here\'s a simple example that logs the city and country:
$.get(\"https://ipinfo.io\", function(response) {
console.log(response.city, response.country);
}, \"jsonp\");
Here\'s a more detailed JSFiddle example that also prints out the full response information, so you can see all of the available details: http://jsfiddle.net/zK5FN/2/
The location will generally be less accurate than the native geolocation details, but it doesn\'t require any user permission.
回答3:
You can use your IP address to get your \'country\', \'city\', \'isp\' etc...
Just use one of the web-services that provide you with a simple api like http://ip-api.com which provide you a JSON service at http://ip-api.com/json. Simple send a Ajax (or Xhr) request and then parse the JSON to get whatever data you need.
var requestUrl = \"http://ip-api.com/json\";
$.ajax({
url: requestUrl,
type: \'GET\',
success: function(json)
{
console.log(\"My country is: \" + json.country);
},
error: function(err)
{
console.log(\"Request failed, error= \" + err);
}
});
回答4:
A very easy to use service is provided by ws.geonames.org
. Here\'s an example URL:
http://ws.geonames.org/countryCode?lat=43.7534932&lng=28.5743187&type=JSON
And here\'s some (jQuery) code which I\'ve added to your code:
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);
});
});
}
Try it on jsfiddle.net
...
回答5:
See ipdata.co a service I built that is fast and has reliable performance thanks to having 10 global endpoints each able to handle >10,000 requests per second!
This answer uses a \'test\' API Key that is very limited and only meant for testing a few calls. Signup for your own Free API Key and get up to 1500 requests daily for development.
This snippet will return the details of your current ip. To lookup other ip addresses, simply append the ip to the https://api.ipdata.co?api-key=test url eg.
https://api.ipdata.co/1.1.1.1?api-key=test
The API also provides an is_eu
field indicating whether the user is in an EU country.
$.get(\"https://api.ipdata.co?api-key=test\", function (response) {
$(\"#response\").html(JSON.stringify(response, null, 4));
}, \"jsonp\");
<script src=\"https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js\"></script>
<pre id=\"response\"></pre>
Here\'s the fiddle; https://jsfiddle.net/ipdata/6wtf0q4g/922/
I also wrote this detailed analysis of 8 of the best IP Geolocation APIs.
回答6:
you can\'t get city location by ip.
here you can get country with jquery:
$.get(\"http://ip-api.com/json\", function(response) {
console.log(response.country);}, \"jsonp\");
回答7:
A free and easy to use service is provided at Webtechriser (click here to read the article) (called wipmania). This one is a JSONP service and requires plain javascript coding with HTML. It can also be used in JQuery. I modified the code a bit to change the output format and this is what I\'ve used and found to be working: (it\'s the code of my HTML page)
<html>
<body>
<p id=\"loc\"></p>
<script type=\"text/javascript\">
var a = document.getElementById(\"loc\");
function jsonpCallback(data) {
a.innerHTML = \"Latitude: \" + data.latitude +
\"<br/>Longitude: \" + data.longitude +
\"<br/>Country: \" + data.address.country;
}
</script>
<script src=\"http://api.wipmania.com/jsonp?callback=jsonpCallback\"
type=\"text/javascript\"></script>
</body>
</html>
PLEASE NOTE: This service gets the location of the visitor without prompting the visitor to choose whether to share their location, unlike the HTML 5 geolocation API (the code that you\'ve written). Therefore, privacy is compromised. So, you should make judicial use of this service.
回答8:
For developers looking for a full-featured geolocation utility, you can have a look at geolocator.js (I\'m the author).
Example below will first try HTML5 Geolocation API to obtain the exact coordinates. If fails or rejected, it will fallback to Geo-IP look-up. Once it gets the coordinates, it will reverse-geocode the coordinates into an address.
var options = {
enableHighAccuracy: true,
timeout: 6000,
maximumAge: 0,
desiredAccuracy: 30,
fallbackToIP: true, // if HTML5 geolocation fails or rejected
addressLookup: true, // get detailed address information
timezone: true,
map: \"my-map\" // this will even create a map for you
};
geolocator.locate(options, function (err, location) {
console.log(err || location);
});
It supports geo-location (via HTML5 or IP lookups), geocoding, address look-ups (reverse geocoding), distance & durations, timezone information and more...
回答9:
You can use ip-api.io to get visitor\'s location. It supports IPv6.
As a bonus it allows to check whether ip address is a tor node, public proxy or spammer.
JavaScript Code:
function getIPDetails() {
var ipAddress = document.getElementById(\"txtIP\").value;
var xhttp = new XMLHttpRequest();
xhttp.onreadystatechange = function () {
if (this.readyState == 4 && this.status == 200) {
console.log(JSON.parse(xhttp.responseText));
}
};
xhttp.open(\"GET\", \"http://ip-api.io/json/\" + ipAddress, true);
xhttp.send();
}
<input type=\"text\" id=\"txtIP\" placeholder=\"Enter the ip address\" />
<button onclick=\"getIPDetails()\">Get IP Details</button>
jQuery Code:
$(document).ready(function () {
$(\'#btnGetIpDetail\').click(function () {
if ($(\'#txtIP\').val() == \'\') {
alert(\'IP address is reqired\');
return false;
}
$.getJSON(\"http://ip-api.io/json/\" + $(\'#txtIP\').val(),
function (result) {
alert(\'Country Name: \' + result.country_name)
console.log(result);
});
});
});
<script src=\"https://code.jquery.com/jquery-1.12.4.js\"></script>
<div>
<input type=\"text\" id=\"txtIP\" />
<button id=\"btnGetIpDetail\">Get Location of IP</button>
</div>