我们如何使用谷歌API获取访客位置

时间:2014-06-23 06:00:34

标签: javascript google-maps-api-3

<script type="text/javascript" src="http://www.google.com/jsapi?key=API KEy"></script>  
 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 = visitor_lat;

    }
    else
    {

      // We implemented the Maxmind method (See source code) or you may want to just leave a message:
      document.getElementById('yourinfo').innerHTML = '<p>Whoops we couldnt find you!</p>';
    }

我使用此代码查找每个访问者的当前位置。但google.loader.ClientLocation返回null值。还有其他方法可以找到访问者的位置。请帮助我。

1 个答案:

答案 0 :(得分:0)

试试这个: HTML5 - 使用地理位置

<!DOCTYPE html>
<html>
<body>

<p id="demo">Click the button to get your coordinates:</p>

<button onclick="getLocation()">Try It</button>

<script>
var x = document.getElementById("demo");
function getLocation() {
if (navigator.geolocation) {
    navigator.geolocation.getCurrentPosition(showPosition);
} else { 
    x.innerHTML = "Geolocation is not supported by this browser.";
}
}

function showPosition(position) {
x.innerHTML="Latitude: " + position.coords.latitude + 
"<br>Longitude: " + position.coords.longitude;  
}