如何使用javascript找到网站访问者位置?

时间:2012-12-26 23:05:48

标签: javascript-events google-analytics javascript unobtrusive-javascript

Google Analytics可以使用javascript库查找访问者位置。如何用javascript完成这个?

2 个答案:

答案 0 :(得分:2)

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

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

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

答案 1 :(得分:1)

Google有一个用于查询访问者位置的API。 Find web visitor's location automatically with javascript and Google APIs

<!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>
相关问题