定位用户位置
使用 GeolocateControl 在地图上显示用户的位置;
<!DOCTYPE html>
<html lang="en">
<head>
<title>定位用户位置</title>
<meta property="og:description" content="使用 GeolocateControl 在地图上显示用户的位置" />
<meta charset='utf-8'>
<meta name="viewport" content="width=device-width, initial-scale=1">
<link rel='stylesheet' href='https://unpkg.com/maplibre-gl@5.5.0/dist/maplibre-gl.css' />
<script src='https://unpkg.com/maplibre-gl@5.5.0/dist/maplibre-gl.js'></script>
<style>
body { margin: 0; padding: 0; }
html, body, #map { height: 100%; }
.info-box {
position: absolute;
bottom: 20px;
left: 50%;
transform: translateX(-50%);
background: white;
padding: 10px;
border-radius: 5px;
box-shadow: 0 0 10px rgba(0,0,0,0.1);
font-family: Arial, sans-serif;
font-size: 14px;
max-width: 300px;
text-align: center;
z-index: 1;
}
</style>
</head>
<body>
<div id="map"></div>
<div class="info-box">
点击右上角的定位按钮<br>以查看您的当前位置
</div>
<script>
const map = new maplibregl.Map({
container: 'map',
style: 'https://api.maptiler.com/maps/streets/style.json?key=get_your_own_OpIi9ZULNHzrESv6T2vL',
center: [0, 0],
zoom: 2
});
// 添加定位控件
const geolocate = new maplibregl.GeolocateControl({
positionOptions: {
enableHighAccuracy: true
},
// 获取位置时自动将地图移动到该位置
trackUserLocation: true,
// 在移动设备上同时显示用户位置的方向
showUserHeading: true
});
// 将控件添加到地图
map.addControl(geolocate);
// 添加定位控件的事件监听器
geolocate.on('geolocate', function(position) {
const lat = position.coords.latitude;
const lng = position.coords.longitude;
const accuracy = position.coords.accuracy;
// 更新信息框内容
const infoBox = document.querySelector('.info-box');
infoBox.innerHTML = `
您的位置:<br>
纬度: ${lat.toFixed(6)}<br>
经度: ${lng.toFixed(6)}<br>
精度: ${accuracy.toFixed(1)}米
`;
});
geolocate.on('error', function(error) {
// 显示错误信息
const infoBox = document.querySelector('.info-box');
if (error.code === 1) { // 权限拒绝
infoBox.innerHTML = '您拒绝了位置访问权限';
} else if (error.code === 2) { // 位置不可用
infoBox.innerHTML = '无法确定您的位置';
} else if (error.code === 3) { // 超时
infoBox.innerHTML = '确定位置超时';
} else {
infoBox.innerHTML = '定位遇到错误: ' + error.message;
}
});
// 添加导航控件
map.addControl(new maplibregl.NavigationControl());
// 地图加载完成后的处理
map.on('load', function() {
// 添加内容...
});
</script>
</body>
</html>