如何使用 HTML5 地理定位经纬度 API?
htmlweb developmentfront end technology更新于 2026/1/7 15:40:17
HTML5 地理定位 API 可让您与您喜爱的网站共享您的位置。JavaScript 代码可以捕获您的经纬度,并将其发送到后端 Web 服务器,从而执行一些复杂的位置感知操作,例如查找本地商家或在地图上显示您的位置。
地理定位 API 可与全局导航器对象(即 Geolocation 对象)的新属性配合使用。

示例
您可以尝试运行以下代码,使用 Geolocation API 查找当前位置,并获取经纬度坐标
<!DOCTYPE HTML>
<html>
<head>
<script type="text/javascript">
function showLocation(position) {
var latitude = position.coords.latitude;
var longitude = position.coords.longitude;
alert("Latitude : " + latitude + " Longitude: " + longitude);
}
function errorHandler(err) {
if(err.code == 1) {
alert("Error: Access is denied!");
} else if( err.code == 2) {
alert("Error: Position is unavailable!");
}
}
function getLocation(){
if(navigator.geolocation){
// timeout at 60000 milliseconds (60 seconds)
var options = {timeout:60000};
navigator.geolocation.getCurrentPosition
(showLocation, errorHandler, options);
} else{
alert("Sorry, browser does not support geolocation!");
}
}
</script>
</head>
<body>
<form>
<input type="button" onclick="getLocation();" value="Get Location"/>
</form>
</body>
</html>
相关文章
有用资源
html 参考教程 - 该教程包含有关 html 的更多信息:https://www.cainiaomax.com/html/

