如何使用Javascript查找web访问者位置?
Google analytics能够使用Javascript库找到访问者的位置。如何使用Javascript实现这一点?navigator.geolocation对象是您向用户代理询问其位置的方式。根据UA的设置,这可能会提示用户允许/拒绝发送数据,也可能不会提示用户允许/拒绝发送数据。此外,地理位置数据本身的精度可能会有很大的变化(不过,它们会给您一个余量或误差,因此您可以将其考虑在内)如何使用Javascript查找web访问者位置?,javascript,google-analytics,dom-events,unobtrusive-javascript,Javascript,Google Analytics,Dom Events,Unobtrusive Javascript,Google analytics能够使用Javascript库找到访问者的位置。如何使用Javascript实现这一点?navigator.geolocation对象是您向用户代理询问其位置的方式。根据UA的设置,这可能会提示用户允许/拒绝发送数据,也可能不会提示用户允许/拒绝发送数据。此外,地理位置数据本身的精度可能会有很大的变化(不过,它们会给您一个余量或误差,因此您可以将其考虑在内) 还有一个watchPosition方法。两者都是异步的,因此您可以传递成功/失败函数来处理返回的对象。谷歌
还有一个watchPosition方法。两者都是异步的,因此您可以传递成功/失败函数来处理返回的对象。谷歌有一个用于查询访问者位置的API
获取web访问者的位置
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\u country=google.loader.ClientLocation.address.country;
visitor\u countrycode=google.loader.ClientLocation.address.country\u code;
document.getElementById('yourinfo').innerHTML='Lat/Lon:'+visitor\u Lat+'/'+visitor\u Lon+'位置:'+visitor\u city+'、'+visitor\u region+'、'+visitor\u country+'('+visitor\u countrycode+');
}
其他的
{
document.getElementById('yourinfo')。innerHTML='Whoops!';
}
。注意:此方法需要访客许可才能获得。你可以尝试使用这个方法。如答案的第二句所述。但在大多数情况下,它具有高精度的优势——如果你需要比某个国家更具体的东西,尤其是在美国以外的国家,基于IP的嗅探就不能被依赖。问题并没有说明他们需要得到的具体程度,但是,例如,如果他们想使用位置来提供方向,那么IP查找是不够的。
if (navigator.geolocation) {
navigator.geolocation.getPosition(
successFunction,
failureFunction
);
} else {
noGeolocationFunction();
};
<!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>