如何获取用户的位置?

时间:2012-10-19 05:11:35

标签: javascript api geolocation google-api

我可以在我的网站上获取用户的IP地址。现在我需要他的国家,城市,地区使用他的IP我得到..我正在使用以下代码尝试Google的Geolocation 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部分并显示Whoops!。 如何获得用户的地理位置。任何其他想法都让我知道。

我已经尝试了以下可以正常工作的代码,但在免费版本中需要6秒的延迟。后来我才知道google正在免费提供这个服务..所以我试试这个。

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

先谢谢你

2 个答案:

答案 0 :(得分:0)

如果您愿意使用HTML5,请访问此tutorial on geolocation

答案 1 :(得分:0)

在客户端使用此功能:

http://services.ipaddresslabs.com/iplocation/locateip?key=SAK58RWP983694534K4Z&ip=local-ip

它与我合作。

顺便说一句,上面的密钥被阻止,你必须得到新密钥。