0
我正在尝试使用地理位置打印当前位置地址,但没有任何内容正在打印在屏幕上。你能帮我吗我在这里错了吗?尝试使用地理位置打印当前位置地址
或者有没有其他方法可以将当前地址存储在变量中?
<!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>