使用 Geolocation API
getCurrentPosition() 方法用于返回用户的位置。
下面的例子返回用户位置的纬度和经度:
实例
<script>
const x = document.getElementById("demo");
function getLocation() {
if (navigator.geolocation) {
navigator.geolocation.getCurrentPosition(showPosition);
} else {
x.innerHTML = "Geolocation is not supported by this browser.";
}
}
实例
function showError(error) {
switch(error.code) {
case error.PERMISSION_DENIED:
x.innerHTML = "User denied the request for Geolocation."
break;
case error.POSITION_UNAVAILABLE:
x.innerHTML = "Location information is unavailable."
break;
case error.TIMEOUT:
x.innerHTML = "The request to get user location timed out."
break;
case error.UNKNOWN_ERROR:
x.innerHTML = "An unknown error occurred."
break;
}
}
亲自试一试
在地图中显示结果
如需在地图中显示结果,您需要访问地图服务,例如 Google 地图。
在下面的例子中,返回的纬度和经度用于在 Google 地图中显示位置(使用静态图像):
实例
function showPosition(position) {
let latlon = position.coords.latitude + "," + position.coords.longitude;
let img_url = "https://maps.googleapis.com/maps/api/staticmap?center=
"+latlon+"&zoom=14&size=400x300&sensor=false&key=YOUR_KEY";
实例
<script>
const x = document.getElementById("demo");
function getLocation() {
if (navigator.geolocation) {
navigator.geolocation.watchPosition(showPosition);
} else {
x.innerHTML = "Geolocation is not supported by this browser.";
}
}
function showPosition(position) {
x.innerHTML = "Latitude: " + position.coords.latitude +
"<br>Longitude: " + position.coords.longitude;
}
</script>
亲自试一试
Web Fetch API
AJAX 简介
JavaScript 和 HTML DOM 参考手册
JavaScript 实例
JavaScript 测验
JavaScript 高级教程