html5中获取当前位置
时间: 2024-03-11 21:06:26 浏览: 25
在 HTML5 中,可以使用浏览器的 Geolocation API 来获取当前位置。以下是获取当前位置的示例代码:
```html
<!DOCTYPE html>
<html>
<head>
<title>获取当前位置</title>
<script>
function getLocation() {
if (navigator.geolocation) {
navigator.geolocation.getCurrentPosition(showPosition);
} else {
alert("该浏览器不支持获取位置信息。");
}
}
function showPosition(position) {
var latitude = position.coords.latitude;
var longitude = position.coords.longitude;
alert("您的当前位置是:纬度 " + latitude + ",经度 " + longitude + "。");
}
</script>
</head>
<body>
<button onclick="getLocation()">获取当前位置</button>
</body>
</html>
```
在上面的示例代码中,点击按钮后会调用 `getLocation()` 函数来获取当前位置。如果浏览器支持 Geolocation API,则调用 `getCurrentPosition()` 方法并将 `showPosition()` 函数作为参数传递进去。`showPosition()` 函数会在获取位置信息成功后被调用,将获取到的纬度和经度信息弹出提示框显示出来。如果浏览器不支持 Geolocation API,则会弹出提示框提示用户。
相关推荐
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![pptx](https://img-home.csdnimg.cn/images/20210720083543.png)