2

谷歌分析能够使用JavaScript库查找访问者位置。这怎么可以用javascript完成?如何使用javascript查找网站访问者位置?

+1

http://stackoverflow.com/questions/3489460/how-to-get-visitors-location-ie-country-using-javascript-geolocation –

+0

[也在该酮](HTTP:// WWW .opal-creations.co.uk /博客/免费的脚本和代码/ GET-A-游客-位置与JavaScript的)。 –

回答

2

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

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

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

+0

注意:此方法将要求访问者获得许可。你可以尝试使用这种方法[这里](http://www.w3schools.com/html/html5_geolocation.asp)。 – Micah

+0

正确,正如答案的第二句所述。但在大多数情况下,它具有高精度的优势 - 如果您需要比国家更特定的任何东西,尤其是美国以外的国家,则不能依赖基于IP的嗅探。这个问题没有说明他们需要得到多么具体,但是如果他们想要使用该位置来提供指导,那么IP查找是不够的。 – Semicolon

1

谷歌有一个查询访问者位置的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> 
相关问题