HTML5 如何获得用户的地理位置
简介: 在这篇文章中,我们将看到如何在HTML5中获取用户的地理位置。
方法: 为了在HTML5中获取用户的地理位置,我们使用地理位置API。HTML5中的地理位置用于在用户允许的情况下与某个网站分享用户的位置。它使用JavaScript来获取纬度和经度。大多数浏览器都支持地理位置API。
语法:
var Location = navigator.geolocation.getCurrentPosition()
上述语法中的变量Location具有以下属性:
- coords.latitude: 始终返回纬度作为一个十进制数
- coords.accuracy: 始终返回位置的准确度
- coords.longitude: 始终返回经度作为一个十进制数
- coords.altitude: 如果有的话,返回海拔高度(以米为单位)
- coords.altitudeAccuracy: 如果有的话,返回位置的海拔准确度
- coords.heading: 如果有的话,返回从北方顺时针方向的角度值
- coords.speed: 如果有的话,返回速度(以米/秒为单位)
- timestamp: 如果有的话,返回响应的日期或时间
示例1: 在这个示例中,我们将使用使用地理位置API创建的Location对象来显示用户权限的经度和纬度。
HTML
<!DOCTYPE html>
<html>
<head>
<title>Latitude and longitude</title>
</head>
<body>
<center>
<h1 class="gfg" style="color:green;">
GeeksforGeeks
</h1>
<h2 id="Location"></h2>
</center>
<script>
var Location = document.getElementById("Location");
navigator.geolocation.getCurrentPosition(showLocation);
function showLocation(position) {
Location.innerHTML =
"Latitude: " + position.coords.latitude +
"<br>Longitude: " + position.coords.longitude;
}
</script>
</body>
</html>
输出:
示例2: 在这个示例中,我们使用Mapbox来显示用户在地图上的位置,使用的是我们获取到的纬度和经度。以下是创建Google地图框的步骤:
步骤1: 将以下脚本添加到HTML页面中以启用Google地图框功能。
<script src=
"https://maps.google.com/maps/api/js?sensor=false"></script>
步骤2: 使用以下方式创建具有经度和纬度坐标的lattlong对象:
var lattlong = new google.maps.LatLng(latitude, longitude);
步骤3: 在 id 为 Map 的 div 中,使用以下代码创建以用户位置为中心的 Mapbox:
var Mapmain = new google.maps.Map(document.getElementById("Map"));
以下是上述方法的实现。
HTML
<!DOCTYPE html>
<html>
<head>
<title>Latitude and longitude</title>
<script src=
"https://maps.google.com/maps/api/js?sensor=false">
</script>
</head>
<body>
<center>
<h1 style="color:green;">
GeeksforGeeks
</h1>
<div id="Map" style="width:700px; height:500px"></div>
</center>
<script>
var Location = document.getElementById("Location");
navigator.geolocation.getCurrentPosition(showLocation);
function showLocation(position) {
latt = position.coords.latitude;
long = position.coords.longitude;
var lattlong = new google.maps.LatLng(latt, long);
var Options = {
center: lattlong,
zoom: 15,
mapTypeControl: true,
navigationControlOptions:
{ style: google.maps.NavigationControlStyle.SMALL }
}
var Mapmain = new google.maps.Map
(document.getElementById("Map"), Options);
var markerpos =
new google.maps.Marker
({ position: lattlong, map: Mapmain });
}
</script>
</body>
</html>
输出: