HTML5 Geolocation API使您可以与自己喜欢的网站共享位置。JavaScript可以捕获您的经度和纬度,可以将其发送到后端Web服务器,并可以进行精美的位置感知操作,例如查找本地商家或在映射上显示您的位置。
让我们看看如何获取当前位置-
<!DOCTYPE HTML>
<html>
<head>
<script>
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){
//超时为60000毫秒(60秒)
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>