Geolocation 与 History API
约 534 字大约 2 分钟
布欧-Lewyon
2026-05-16
首页 › HTML › HTML5 API › Geolocation 与 History API
Geolocation API
获取用户的地理位置。
获取当前位置
navigator.geolocation.getCurrentPosition(
(position) => {
console.log('纬度:', position.coords.latitude);
console.log('经度:', position.coords.longitude);
console.log('精度:', position.coords.accuracy); // 单位米
console.log('海拔:', position.coords.altitude); // 可能为 null
},
(error) => {
switch (error.code) {
case error.PERMISSION_DENIED: // 1 - 用户拒绝
console.log('用户拒绝了位置请求');
break;
case error.POSITION_UNAVAILABLE: // 2 - 位置不可用
console.log('无法获取位置');
break;
case error.TIMEOUT: // 3 - 超时
console.log('定位超时');
break;
}
},
{
enableHighAccuracy: true, // 高精度模式(耗电)
timeout: 5000, // 超时时间(ms)
maximumAge: 60000 // 缓存有效期(ms)
}
);持续监听位置
const watchId = navigator.geolocation.watchPosition(
(position) => {
console.log('位置更新:', position.coords.latitude, position.coords.longitude);
},
(error) => { console.error(error); }
);
// 停止监听
navigator.geolocation.clearWatch(watchId);权限提示
浏览器首次调用 Geolocation API 会弹出权限询问框:
- 必须通过 HTTPS 访问(或 localhost)
- 用户拒绝后无法再次弹出,需用户自行在浏览器设置中更改
History API
SPA(单页应用)的核心基础——URL 改变但不刷新页面。
pushState
// pushState(state, title, url)
history.pushState({ page: 1 }, '页面1', '/page1');
history.pushState({ page: 2 }, '页面2', '/page2');
history.pushState({ page: 3 }, '页面3', '/page3');state:与 URL 关联的状态对象title:大多数浏览器忽略此参数,传入空字符串url:新的 URL(不会加载页面)
replaceState
替换当前历史记录(不产生新条目):
history.replaceState({ page: 'home' }, '', '/home');popstate 事件
用户点击浏览器的前进/后退按钮时触发:
window.addEventListener('popstate', (event) => {
console.log('状态:', event.state); // 对应的 state 对象
console.log('当前 URL:', document.location.href);
// 根据 state 更新页面内容
updateContent(event.state);
});注意:
pushState/replaceState不会触发popstate事件。
SPA 路由基础示例
<nav>
<a href="/home" onclick="navigate(event, '/home')">首页</a>
<a href="/about" onclick="navigate(event, '/about')">关于</a>
</nav>
<div id="content">欢迎</div>
<script>
function navigate(event, path) {
event.preventDefault();
history.pushState({ path }, '', path);
updateContent(path);
}
function updateContent(path) {
const content = {
'/home': '<h1>首页</h1>',
'/about': '<h1>关于我们</h1>',
};
document.getElementById('content').innerHTML = content[path] || '<h1>404</h1>';
}
// 处理前进/后退
window.addEventListener('popstate', (event) => {
updateContent(event.state?.path || '/home');
});
</script>小结
| API | 主要方法 |
|---|---|
| Geolocation | getCurrentPosition() / watchPosition() / clearWatch() |
| History | pushState() / replaceState() / popstate 事件 |
上一节:Web Storage 下一节:Drag & Drop 与 File API
