Getting GPS Location
HTML5 provides the navigator.geolocation API, which lets a browser request the user's geographic location. When it is called, the browser will display a permission prompt. Location information such as latitude and longitude can only be read after the user grants permission.
Note that modern browsers usually require the page to run in an HTTPS environment, or to be tested locally under localhost. Otherwise, even if the code is correct, it may still be unable to retrieve the location.
<script type="text/javascript">
if (navigator.geolocation) {
navigator.geolocation.getCurrentPosition(onSuccess, onError);
} else {
alert("您的浏览器不支持使用 HTML5 来获取地理位置服务");
}
// 定位数据获取成功响应
function onSuccess(position) {
alert('纬度: ' + position.coords.latitude + 'n' +
'经度: ' + position.coords.longitude + 'n' +
'海拔: ' + position.coords.altitude + 'n' +
'水平精度: ' + position.coords.accuracy + 'n' +
'垂直精度: ' + position.coords.altitudeAccuracy);
}
// 定位数据获取失败响应
function onError(error) {
switch (error.code) {
case error.PERMISSION_DENIED:
alert("您拒绝了获取地理位置的请求");
break;
case error.POSITION_UNAVAILABLE:
alert("位置信息不可用");
break;
case error.TIMEOUT:
alert("请求您的地理位置超时");
break;
case error.UNKNOWN_ERROR:
alert("未知错误");
break;
}
}
</script>
Field Descriptions
position.coords.latitude: Latitude.position.coords.longitude: Longitude.position.coords.altitude: Altitude. If the device or browser cannot provide it, this may benull.position.coords.accuracy: Horizontal accuracy, usually measured in meters.position.coords.altitudeAccuracy: Vertical accuracy. If it cannot be provided, this may benull.
Reproducible Check
Save the code above as an HTML file and open it in a browser that supports location permissions. If the browser blocks the location request, first confirm that the page is being accessed over HTTPS, and check the browser and system location permission settings.
