尝试使用geolcoation打印当前的lcoation地址

时间:2017-06-16 11:11:43

标签: geolocation

我正在尝试使用地理位置打印当前位置地址,但屏幕上没有打印任何内容。能帮到我,我在哪里错了吗?

或者还有其他方法可以将当前地址存储在变量中吗?

<!DOCTYPE html>
<html>
<body>

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

<p id="demo"></p>

<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) {

 var request = new XMLHttpRequest();
 var method = 'GET';
 var url = 'http://maps.googleapis.com/maps/api/geocode/json?latlng='+position.coords.latitude+','+position.coords.longitude;
 var async = true;

 request.open(method, url, async);

 request.onreadystatechange = function(){

var data = JSON.parse(request.responseText);
var address = data.results[0];
x.innerHTML = address.formatted_address;          
        };
}
</script>

</body>
</html>

1 个答案:

答案 0 :(得分:0)

这应该有效:JSFIDDLE

您遗失了request.send();,也没有查看request.readyState

<!DOCTYPE html>
<html>

  <body>

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

    <p id="demo"></p>

    <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) {

        var request = new XMLHttpRequest();
        var method = 'GET';
        var url = '//maps.googleapis.com/maps/api/geocode/json?latlng=' + position.coords.latitude + ',' + position.coords.longitude;
        var async = true;

        request.open(method, url, async);
        request.setRequestHeader('Accept', 'application/json');
        request.onreadystatechange = function() {
          if (request.readyState == XMLHttpRequest.DONE) {
            var data = JSON.parse(request.responseText);
            var address = data.results[0];
            x.innerHTML = address.formatted_address;
          }
        };
        request.send();
      }

    </script>

  </body>

</html>