如何使用 Javascript 查找网络访问者位置?[关闭]

How can I find a web visitors location using Javascript? [closed]

提问人:user1530249 提问时间:12/27/2012 最后编辑:Brian Tompsett - 汤莱恩user1530249 更新时间:1/15/2020 访问量:2460


答:

2赞 Semicolon 12/27/2012 #1

navigator.geolocation 对象是您向用户代理询问其位置的方式。根据 UA 的设置,这可能会也可能不会提示用户允许/拒绝发送数据。此外,地理位置数据本身的精度可能非常可变(不过,它们会给你一个余量或误差,所以你可以把它考虑在内)。

if (navigator.geolocation) {
    navigator.geolocation.getPosition(
        successFunction,
        failureFunction
    );
} else {
    noGeolocationFunction();
};

还有一个 watchPosition 方法。两者都是异步的,因此您可以向它传递成功/失败函数来处理返回的对象。

评论

0赞 Micah 12/27/2012
注意:此方法需要访问者权限才能获得。您可以在此处尝试使用此方法。
0赞 Semicolon 12/27/2012
没错,正如答案的第二句话所指出的。但在大多数情况下,它具有高精度的优势 - 如果您需要比某个国家/地区更具体的东西,尤其是美国以外的国家,则不能依赖基于 IP 的嗅探。该问题没有说明他们需要获得多具体的信息,但是,例如,如果他们想使用该位置来提供方向,那么IP查找是不够的。
1赞 Micah 12/27/2012 #2

Google 有一个用于查询访问者位置的 API。使用 javascript 和 Google API 自动查找网络访问者的位置

<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
<html>
    <head>
        <title>Get web visitor's location</title>
        <meta name="robots" value="none" />
    </head>
    <body>
    <div id="yourinfo"></div>
    <script type="text/javascript" src="http://www.google.com/jsapi?key=[apikey]"></script>
    <script type="text/javascript">
        if(google.loader.ClientLocation)
        {
            visitor_lat = google.loader.ClientLocation.latitude;
            visitor_lon = google.loader.ClientLocation.longitude;
            visitor_city = google.loader.ClientLocation.address.city;
            visitor_region = google.loader.ClientLocation.address.region;
            visitor_country = google.loader.ClientLocation.address.country;
            visitor_countrycode = google.loader.ClientLocation.address.country_code;
            document.getElementById('yourinfo').innerHTML = '<p>Lat/Lon: ' + visitor_lat + ' / ' + visitor_lon + '</p><p>Location: ' + visitor_city + ', ' + visitor_region + ', ' + visitor_country + ' (' + visitor_countrycode + ')</p>';
        }
        else
        {
            document.getElementById('yourinfo').innerHTML = '<p>Whoops!</p>';
        }
    </script>
    </body>
</html>