Javascript 如何使用地理定位获取访问者的位置(即国家/地区)?

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/3489460/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-23 04:52:08  来源:igfitidea点击:

How to get visitor's location (i.e. country) using geolocation?

javascriptgeolocation

提问by Gal

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 librarywhich worked well in this examplebut 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?

无论如何,您知道我如何从纬度和经度值简单地返回一个包含国家、城市等信息的数组吗?

采纳答案by Galen

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, ipregistryor ip2location). This will be accurate most of the time.

如果您只需要他们的国家,则不需要定位用户。您可以在任何 IP 到位置服务(如maxmindipregistryip2location)中查找他们的 IP 地址。这在大多数情况下都是准确的。

If you really need to get their location, you can get their lat/lng with that method, then query Google'sor Yahoo'sreverse geocoding service.

如果您确实需要获取他们的位置,您可以使用该方法获取他们的 lat/lng,然后查询GoogleYahoo 的反向地理编码服务。

回答by Ben Dowling

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:

为此,您可以使用我的服务http://ipinfo.io。它将为您提供客户端 IP、主机名、地理位置信息(城市、地区、国家、区号、邮政编码等)和网络所有者。这是一个记录城市和国家的简单示例:

$.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/

这是一个更详细的 JSFiddle 示例,它也打印出完整的响应信息,因此您可以查看所有可用的详细信息: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.

该位置通常不如本地地理位置详细信息准确,但它不需要任何用户许可。

回答by Gil Epshtain

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.comwhich 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.

你可以用你的IP地址,让您的“国家”,“城市”,“ISP”等等
的网络服务,为您提供一个简单的API一样的只是使用一个http://ip-api.com这在http://ip-api.com/json为您提供 JSON 服务。简单地发送一个 Ajax(或 Xhr)请求,然后解析 JSON 以获取您需要的任何数据。

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);
  }
});

回答by Jonathan

See ipdata.coa 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!

请参阅ipdata.co,这是我构建的一项服务,由于拥有 10 个全局端点,每个端点每秒能够处理超过 10,000 个请求,因此速度快且性能可靠!

This answer uses a 'test' API Key that is very limited and only meant for testing a few calls. Signupfor your own Free API Key and get up to 1500 requests daily for development.

这个答案使用了一个非常有限的“测试”API 密钥,仅用于测试几个调用。注册您自己的免费 API 密钥,每天最多可收到 1500 个开发请求。

This snippet will return the details of your currentip. To lookup other ip addresses, simply append the ip to the https://api.ipdata.co?api-key=testurl eg.

此代码段将返回您当前ip的详细信息。要查找其他 ip 地址,只需将 ip 附加到https://api.ipdata.co?api-key=testurl 例如。

https://api.ipdata.co/1.1.1.1?api-key=test

The API also provides an is_eufield indicating whether the user is in an EU country.

API 还提供了一个is_eu字段,指示用户是否在欧盟国家/地区。

$.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/

这是小提琴;https://jsfiddle.net/ipdata/6wtf0q4g/922/

I also wrote thisdetailed analysis of 8 of the best IP Geolocation APIs.

我也写了这个最佳的IP地理位置API的8详细分析。

回答by anmml

you can't get city location by ip. here you can get country with jquery:

您无法通过 ip 获取城市位置。在这里,您可以使用 jquery 获取国家/地区:

$.get("http://ip-api.com/json", function(response) {
console.log(response.country);}, "jsonp");

回答by hippietrail

A very easy to use service is provided by ws.geonames.org. Here's an example URL:

提供了一项非常易于使用的服务ws.geonames.org。这是一个示例网址:

http://ws.geonames.org/countryCode?lat=43.7534932&lng=28.5743187&type=JSON

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:

这是我添加到您的代码中的一些(jQuery)代码:

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...

试穿jsfiddle.net...

回答by hippietrail

A free and easy to use service is provided at Webtechriser (click here to read the article)(called wipmania). This one is a JSONPservice and requires plain javascriptcoding 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)

Webtechriser提供免费且易于使用的服务(单击此处阅读文章)(称为wipmania)。这是一个JSONP服务,需要使用HTML 进行javascript编码。它也可以在JQuery 中使用。我稍微修改了代码以更改输出格式,这就是我使用过并发现有效的方法:(这是我的 HTML 页面的代码)

<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 withoutprompting 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.

请注意:HTML 5 地理定位 API(您编写的代码)不同,此服务会获取访问者的位置,而不会提示访问者选择是否共享他们的位置。因此,隐私受到损害。因此,您应该对这项服务进行司法使用。

回答by Onur Y?ld?r?m

For developers looking for a full-featured geolocation utility, you can have a look at geolocator.js(I'm the author).

对于正在寻找功能齐全的地理定位实用程序的开发人员,您可以查看geolocator.js(我是作者)。

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.

下面的示例将首先尝试 HTML5 Geolocation API 来获取准确的坐标。如果失败或被拒绝,它将回退到 Geo-IP 查找。一旦获得坐标,它就会将坐标反向地理编码为地址。

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...

它支持地理位置(通过 HTML5 或 IP 查找)、地理编码、地址查找(反向地理编码)、距离和持续时间、时区信息等等...

回答by Vindhyachal Kumar

You can use ip-api.ioto get visitor's location. It supports IPv6.

您可以使用ip-api.io来获取访问者的位置。它支持 IPv6。

As a bonus it allows to check whether ip address is a tor node, public proxy or spammer.

作为奖励,它允许检查 IP 地址是 Tor 节点、公共代理还是垃圾邮件发送者。

JavaScript Code:

JavaScript 代码:

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:

jQuery代码:

$(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>