html5中获取当前位置
时间: 2024-03-11 11:04:11 浏览: 26
要在 HTML5 中获取当前位置,可以使用浏览器提供的 Geolocation API。以下是一个基本的示例:
```html
<!DOCTYPE html>
<html>
<head>
<meta charset="utf-8">
<title>获取当前位置</title>
</head>
<body>
<p id="demo">点击按钮获取当前位置</p>
<button onclick="getLocation()">获取位置</button>
<script>
function getLocation() {
if (navigator.geolocation) {
navigator.geolocation.getCurrentPosition(showPosition);
} else {
document.getElementById("demo").innerHTML = "Geolocation is not supported by this browser.";
}
}
function showPosition(position) {
document.getElementById("demo").innerHTML = "Latitude: " + position.coords.latitude +
"<br>Longitude: " + position.coords.longitude;
}
</script>
</body>
</html>
```
当用户点击“获取位置”按钮时,`getLocation()` 函数将会调用 `getCurrentPosition()` 方法来请求获取用户的当前位置。如果浏览器支持 Geolocation API,则会调用 `showPosition()` 函数来展示经纬度信息。否则,将会展示一个错误信息。