2012-10-19 64 views
3

我可以在我的网站上获得用户的IP地址。现在我需要他的国家,城市,用他的IP我得到了区域..我想谷歌的地理位置API用下面的代码,如何获取用户的位置?

<div id="yourinfo"></div> 
    <script type="text/javascript" src="http://www.google.com/jsapi?key=ABQIAAAAp04yNttlQq-7b4aZI_jL5hQYPm-xtd00hTQOC0OXpAMO40FHAxQMnH50uBbWoKVHwgpklyirDEregg"></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> 

真的该代码是不是为我工作。它正在执行else部分并显示哎呀! 如何获取用户的地理位置。任何其他的想法让我知道。

我已经尝试了下面的代码,它运行良好,但在免费版本中需要6秒的延迟。后来我才知道谷歌是免费提供这个服务..所以我尝试了这一点。

http://services.ipaddresslabs.com/iplocation/locateip?key=SAK58RWP983694534K4Z&ip=".$ClientIP 

预先感谢您

+0

我的一个炸我告诉我,这个Google地理定位API只能在美国工作。这是真的吗? –

+0

是否有任何其他方式地理编码与谷歌API的IP我应该得到XML响应。 –

+0

我刚刚尝试使用从google.com导入的API链接,并且它在[this jsFiddle](http://jsfiddle.net/nErrt/)中运行良好。也许你在检索脚本时遇到问题(尝试直接访问API的URL以查看它是否正确地返回JS)。另外,根据Google脚本的编写方式,如果您已经定义了'window.google',那么脚本将无法加载(请参阅脚本开头处的if结构)。另外,geoloc在美国以外工作,因为我在欧洲,并且拥有非常准确的geoloc。希望这可以帮助。 –

回答