HTML Geolocation API 用于获取用户的地理位置。
由于这可能会损害隐私,因此除非用户批准,否则该职位不可用。
对于具有 GPS 的设备(例如智能手机)来说,地理定位最为准确。
所有浏览器都支持 Geolocation API:
Yes | Yes | Yes | Yes | Yes |
地理定位 API 仅适用于安全上下文,例如 作为 HTTPS。
如果您的网站托管在非安全源(例如 HTTP)上 获取用户位置的请求将不再起作用。
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 showPosition(position) {
x.innerHTML = "Latitude: " + position.coords.latitude +
"<br>Longitude: " + position.coords.longitude;
}
</script>
自己尝试一下 →
<!DOCTYPE html>
<html>
<body>
<h2>JavaScript Geolocation API</h2>
<p>Click the button to get your coordinates.</p>
<button onclick="getLocation()">Try It</button>
<p id="demo"></p>
<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 showPosition(position) {
x.innerHTML = "Latitude: " + position.coords.latitude +
"<br>Longitude: " + position.coords.longitude;
}
</script>
</body>
</html>
示例解释:
检查是否支持地理位置
如果支持,请运行 getCurrentPosition() 方法。如果没有,则向用户显示一条消息
如果 getCurrentPosition() 方法成功,它会返回一个坐标对象给参数中指定的函数(showPosition)
showPosition() 函数输出纬度和经度
上面的示例是一个非常基本的地理定位脚本,没有错误处理。
getCurrentPosition()
方法的第二个参数用于处理 错误。它指定在无法获取用户位置时要运行的函数:
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;
}
}
自己尝试一下 →
<!DOCTYPE html>
<html>
<body>
<h2>JavaScript Geolocation API</h2>
<p>Click the button to get your coordinates.</p>
<button onclick="getLocation()">Try It</button>
<p id="demo"></p>
<script>
const x = document.getElementById("demo");
function getLocation() {
if (navigator.geolocation) {
navigator.geolocation.getCurrentPosition(showPosition, showError);
} else {
x.innerHTML = "Geolocation is not supported by this browser.";
}
}
function showPosition(position) {
x.innerHTML = "Latitude: " + position.coords.latitude +
"<br>Longitude: " + position.coords.longitude;
}
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;
}
}
</script>
</body>
</html>
要在地图中显示结果,您需要访问地图服务,例如 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";
document.getElementById("mapholder").innerHTML = "<img src='"+img_url+"'>";
}
自己尝试一下
<!DOCTYPE html>
<html>
<body>
<h1>HTML Geolocation</h1>
<p id="demo">Click the button to get your position.</p>
<button onclick="getLocation()">Try It</button>
<div id="mapholder"></div>
<script>
const x = document.getElementById("demo");
function getLocation() {
if (navigator.geolocation) {
navigator.geolocation.getCurrentPosition(showPosition, showError);
} else {
x.innerHTML = "Geolocation is not supported by this browser.";
}
}
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&key=AIzaSyBu-916DdpKAjTmJNIgngS6HL_kDIKU0aU";
document.getElementById("mapholder").innerHTML = "<img src='"+img_url+"'>";
}
//To use this code on your website, get a free API key from Google.
//Read more at: https://www.w3schools.com/graphics/google_maps_basic.asp
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;
}
}
</script>
</body>
</html>
如何显示带有标记、缩放和拖动选项的交互式 Google 地图。
谷歌地图脚本
<!DOCTYPE html>
<html>
<body>
<h1>HTML Geolocation</h1>
<p id="demo">Click the button to get your position.</p>
<button onclick="getLocation()">Try It</button>
<div id="mapholder"></div>
<script src="https://maps.google.com/maps/api/js?key=AIzaSyBu-916DdpKAjTmJNIgngS6HL_kDIKU0aU"></script>
<!--
To use this code on your website, get a free API key from Google.
Read more at: https://www.w3schools.com/graphics/google_maps_basic.asp
-->
<script>
const x = document.getElementById("demo");
function getLocation() {
if (navigator.geolocation) {
navigator.geolocation.getCurrentPosition(showPosition, showError);
} else {
x.innerHTML = "Geolocation is not supported by this browser.";
}
}
function showPosition(position) {
let lat = position.coords.latitude;
let lon = position.coords.longitude;
const latlon = new google.maps.LatLng(lat, lon)
const mapholder = document.getElementById('mapholder')
mapholder.style.height = '250px';
mapholder.style.width = '500px';
var myOptions = {
center:latlon,zoom:14,
mapTypeId:google.maps.MapTypeId.ROADMAP,
mapTypeControl:false,
navigationControlOptions:{style:google.maps.NavigationControlStyle.SMALL}
}
const map = new google.maps.Map(document.getElementById("mapholder"), myOptions);
const marker = new google.maps.Marker({position:latlon,map:map,title:"You are here!"});
}
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;
}
}
</script>
</body>
</html>
本页面演示了如何在地图上显示用户的位置。
地理定位对于特定位置信息也非常有用,例如:
最新的本地信息
显示用户附近的兴趣点
路线规划导航 (GPS)
getCurrentPosition()
方法在成功时返回一个对象。纬度, 始终返回经度和精度属性。返回其他属性 如果可供使用的话:
十进制数形式的纬度(始终返回)
十进制数形式的经度(始终返回)
位置精度(始终返回)
平均海平面以上的高度(以米为单位)(如果有则返回)
位置的高度精度(如果有则返回)
航向为从北顺时针旋转的度数(如果可用则返回)
以米每秒为单位的速度(如果可用则返回)
响应的日期/时间(如果可用则返回)
Geolocation 对象还有其他有趣的方法:
watchPosition()
- 返回用户的当前位置并继续 当用户移动时返回更新的位置(就像汽车中的 GPS)。
clearWatch()
- 停止 watchPosition()
方法。
下面的示例显示了 watchPosition()
方法。您需要一个准确的 GPS 设备来测试这一点(例如 手机):
<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>
自己尝试一下 →
<!DOCTYPE html>
<html>
<body>
<h2>JavaScript Geolocation API</h2>
<p>Click the button to get your coordinates.</p>
<button onclick="getLocation()">Try It</button>
<p id="demo"></p>
<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>
</body>
</html>