本文目录导读:

- 方式一:使用 HTML5 Geolocation API(前端,浏览器端)
- 方式二:使用 IP 地址查询(后端或 Node.js 脚本)
- 方式三:移动端(React Native / Flutter)脚本
- 总结选择建议
基于浏览器的 HTML5 Geolocation API(前端脚本)和基于 IP 地址的查询(后端或 API 脚本),下面分别介绍这两种方式的实现脚本。
使用 HTML5 Geolocation API(前端,浏览器端)
这是最精确、最常见的方式,利用用户的设备(GPS、WiFi、基站)获取经纬度。
优点: 精度高(可达米级)。
缺点: 需要用户授权;在非 HTTPS 页面可能被浏览器禁止。
HTML + JavaScript 示例代码
<!DOCTYPE html>
<html>
<head>获取地理位置</title>
</head>
<body>
<h2>地理位置信息</h2>
<button onclick="getLocation()">获取我的位置</button>
<p id="demo"></p>
<script>
function getLocation() {
const output = document.getElementById("demo");
if (!navigator.geolocation) {
output.innerHTML = "浏览器不支持地理定位。";
return;
}
function success(position) {
const latitude = position.coords.latitude;
const longitude = position.coords.longitude;
const accuracy = position.coords.accuracy; // 精度(米)
output.innerHTML = `
纬度: ${latitude} <br>
经度: ${longitude} <br>
精度: ${accuracy} 米
`;
}
function error(err) {
let msg = "";
switch(err.code) {
case err.PERMISSION_DENIED:
msg = "用户拒绝了位置请求。";
break;
case err.POSITION_UNAVAILABLE:
msg = "位置信息不可用。";
break;
case err.TIMEOUT:
msg = "请求用户位置超时。";
break;
default:
msg = "未知错误。";
}
output.innerHTML = msg;
}
// 请求位置(超时10秒,高精度)
navigator.geolocation.getCurrentPosition(success, error, {
enableHighAccuracy: true,
timeout: 10000,
maximumAge: 0
});
}
</script>
</body>
</html>
注意:
- 必须通过 HTTPS 或 localhost 才能正常工作。
enableHighAccuracy: true会使用 GPS 等更耗电但更精确的方式。- 用户会看到一个弹窗请求授权。
使用 IP 地址查询(后端或 Node.js 脚本)
如果只需要大概的城市/区域级别(精度通常几公里到几十公里),可以通过 IP 查询,这种方式不需要用户授权。
优点: 无需用户操作,始终可用。
缺点: 精度低,无法获得精确经纬度(尤其是VPN或代理环境下)。
1 使用免费 API(简单 HTTP 请求)
常见免费 IP 地理定位 API 有:
ip-api.com(免费,支持 HTTP,无需 key)ipinfo.io(免费版有限制,需要 token)
示例:浏览器端使用 fetch 调用 ip-api.com(注意跨域问题)
// 获取访客自己的IP地理位置(浏览器环境)
fetch('http://ip-api.com/json/?fields=status,message,country,regionName,city,lat,lon,query')
.then(response => response.json())
.then(data => {
if (data.status === 'success') {
console.log('IP:', data.query);
console.log('国家:', data.country);
console.log('省份:', data.regionName);
console.log('城市:', data.city);
console.log('纬度:', data.lat);
console.log('经度:', data.lon);
} else {
console.log('查询失败:', data.message);
}
})
.catch(err => console.error('请求失败', err));
注意: 浏览器环境可能有 CORS 限制,建议通过后端代理,或在 Node.js 中使用 axios/node-fetch。
2 Node.js 后端示例(使用 axios)
const axios = require('axios');
async function getLocationByIP(ip) {
try {
// 如果不传 ip,ip-api.com 会自动获取请求来源的IP
const response = await axios.get(`http://ip-api.com/json/${ip}?fields=status,country,regionName,city,lat,lon`);
if (response.data.status === 'success') {
return {
ip: ip || 'auto',
country: response.data.country,
region: response.data.regionName,
city: response.data.city,
latitude: response.data.lat,
longitude: response.data.lon
};
} else {
throw new Error('查询失败');
}
} catch (error) {
console.error('获取地理位置失败:', error.message);
return null;
}
}
// 使用示例:获取服务端的公网IP地理位置(或传入具体IP)
getLocationByIP('8.8.8.8').then(location => console.log(location));
移动端(React Native / Flutter)脚本
如果是开发移动 App,可以调用原生定位模块。
React Native 示例(使用 @react-native-community/geolocation):
import Geolocation from '@react-native-community/geolocation';
function getPosition() {
Geolocation.getCurrentPosition(
pos => {
console.log('纬度:', pos.coords.latitude);
console.log('经度:', pos.coords.longitude);
},
error => console.log(error.message),
{ enableHighAccuracy: true, timeout: 15000 }
);
}
Flutter 示例(使用 geolocator 包):
import 'package:geolocator/geolocator.dart';
void getLocation() async {
bool serviceEnabled = await Geolocator.isLocationServiceEnabled();
if (!serviceEnabled) {
print('位置服务未开启');
return;
}
LocationPermission permission = await Geolocator.checkPermission();
if (permission == LocationPermission.denied) {
permission = await Geolocator.requestPermission();
if (permission == LocationPermission.denied) {
print('权限被拒绝');
return;
}
}
Position position = await Geolocator.getCurrentPosition(
desiredAccuracy: LocationAccuracy.high
);
print('纬度: ${position.latitude}, 经度: ${position.longitude}');
}
总结选择建议
| 使用场景 | 推荐方式 | 精度 | 是否需要用户授权 |
|---|---|---|---|
| 网页端(精确位置) | HTML5 Geolocation API | 高(米级) | 是 |
| 网页端(粗略位置) | IP 查询(如 ip-api.com) | 低(城市级) | 否 |
| 后端服务 | IP 查询 | 低(城市级) | 否 |
| 移动 App | 原生定位 API | 高(米级) | 是 |
| 需要持续追踪 | watchPosition 替代 getCurrentPosition |
高 | 是 |
安全提示: 在收集用户地理位置前,请确保遵守当地隐私法规(如 GDPR、CCPA),并明确告知用户数据用途。