HTML5获取地理位置定位信息
<!DOCTYPE html>
<html>
<body>
<p>点击按钮获取位置信息:</p>
<button onclick="getLocation()">点击这里</button>
<p id="demo"></p>
<script>
var x = document.getElementById("demo");
function getLocation() {
if (navigator.geolocation) {
navigator.geolocation.getCurrentPosition(showPosition, showError);
} else {
x.innerHTML = "Geolocation is not supported by this browser.";
}
}
function showPosition(position) {
x.innerHTML = "Latitude: " + position.coords.latitude +
"<br>Longitude: " + position.coords.longitude;
}
function showError(error) {
switch(error.code) {
case error.PERMISSION_DENIED:
x.innerHTML = "User denied the request for Geolocation."
break;
case error.POSITION_UNAVAILABLE:
x.innerHTML = "Location information is unavailable."
break;
case error.TIMEOUT:
x.innerHTML = "The request to get user location timed out."
break;
case error.UNKNOWN_ERROR:
x.innerHTML = "An unknown error occurred."
break;
}
}
</script>
</body>
</html>
这段代码使用HTML5的Geolocation API来获取用户的当前位置。如果用户允许,则显示位置信息(纬度和经度),否则显示错误信息。这个例子简单明了地展示了如何在网页中集成地理位置定位功能。
评论已关闭