// 檢查支援度
if (navigator.geolocation) {
// 取得目前位置 (非同步)
navigator.geolocation.getCurrentPosition(successCallback, errorCallback, options);
// 持續監看位置變化 (行動裝置適用)
var watchId = navigator.geolocation.watchPosition(successCallback, errorCallback, options);
// 停止監看
navigator.geolocation.clearWatch(watchId);
} else {
alert('瀏覽器不支援地理定位');
}
position.coords 包含 latitude, longitude, accuracy (精度米), altitude, heading, speed。error.code (1:PERMISSION_DENIED, 2:POSITION_UNAVAILABLE, 3:TIMEOUT), error.message。{ enableHighAccuracy: true, timeout: 10000, maximumAge: 0 }。<!DOCTYPE html>
<html>
<head>
<meta charset="utf-8">
<title>百度地圖定位示範</title>
<script type="text/javascript" src="https://api.map.baidu.com/api?v=3.0&ak=您的AK"></script>
<style>
#map { width: 100%; height: 400px; }
#result { padding: 10px; background: #f5f5f5; margin-top: 10px; }
</style>
</head>
<body>
<button onclick="getLocation()">獲取我的位置</button>
<div id="map"></div>
<div id="result"></div>
<script>
var map = new BMap.Map('map');
var geocoder = new BMap.Geocoder();
function getLocation() {
var resultDiv = document.getElementById('result');
resultDiv.innerHTML = '定位中...';
if (!navigator.geolocation) {
resultDiv.innerHTML = '瀏覽器不支援地理定位';
return;
}
navigator.geolocation.getCurrentPosition(
function(position) {
var lat = position.coords.latitude;
var lng = position.coords.longitude;
var accuracy = position.coords.accuracy;
// 顯示座標
resultDiv.innerHTML = '座標: ' + lng.toFixed(6) + ', ' + lat.toFixed(6) +
' (精度: ' + accuracy.toFixed(1) + ' 米)';
// 百度地圖坐標系轉換 (GPS/GCJ02 → BD09)
var gpsPoint = new BMap.Point(lng, lat);
var convertor = new BMap.Convertor();
convertor.translate([gpsPoint], 1, 5, function(data) {
if (data.status === 0 && data.points.length > 0) {
var bdPoint = data.points[0];
map.centerAndZoom(bdPoint, 15);
var marker = new BMap.Marker(bdPoint);
map.addOverlay(marker);
// 逆地理編碼:座標 → 地址
geocoder.getLocation(bdPoint, function(rs) {
var addComp = rs.addressComponents;
var address = addComp.province + addComp.city + addComp.district + addComp.street + (addComp.streetNumber || '');
resultDiv.innerHTML += '
地址: ' + address;
});
}
});
},
function(error) {
var msg = '定位失敗: ';
switch (error.code) {
case 1: msg += '使用者拒絕授權'; break;
case 2: msg += '位置不可用'; break;
case 3: msg += '請求逾時'; break;
}
resultDiv.innerHTML = msg + ' (' + error.message + ')';
},
{ enableHighAccuracy: true, timeout: 10000, maximumAge: 0 }
);
}
</script>
</body>
</html>
BMap.Convertor().translate(points, 1, 5, callback) 轉換 (1=GPS→BD09, 5=GCJ02→BD09),否則標記位置會偏移數百米。enableHighAccuracy: true 使用 GPS (精度 ~10m,耗電、慢);false 使用 Wi-Fi/基地台/IP (精度 ~100-1000m,快、省電)。// 百度 IP 定位 API (需 AK)
function ipFallback() {
var xhr = new XMLHttpRequest();
xhr.open('GET', 'https://api.map.baidu.com/location/ip?ak=您的AK&coor=bd09ll');
xhr.onload = function() {
if (xhr.status === 200) {
var data = JSON.parse(xhr.responseText);
if (data.status === 0) {
var point = new BMap.Point(data.content.point.x, data.content.point.y);
map.centerAndZoom(point, 11);
document.getElementById('result').innerHTML = 'IP 定位 (約略): ' + data.content.address;
}
}
};
xhr.send();
}
| 服務商 | JS API | 定位 API | 優點 | 適用場景 |
|---|---|---|---|---|
| 百度地圖 | 功能豐富 | IP/逆地理編碼 | 國內詮釋最佳、支援 BD09 | 國內專案、需詳細中文地址 |
| 高德地圖 | 輕量、快 | IP/逆地理/周邊搜尋 | 免費額度大、文檔好 | 國內專案、高併發 |
| 騰訊位置服務 | 整合微信生態 | 微信 JSAPI 定位 | 微信小程序/公眾號首選 | 微信生態專案 |
| Google Maps | 全球最完善 | Geocoding/Places | 國際化、資料豐富 | 海外專案 |
| Leaflet + OSM | 開源、免費 | 需自建/第三方 | 無商業授權、可離線 | 開源專案、內網、成本敏感 |
HTML5 Geolocation + 百度地圖 API 是國內 Web 定位的經典組合。關鍵點:**HTTPS 環境、AK 管理、座標系轉換 (GPS→BD09)、授權失敗備援 (IP 定位)**。現代專案建議評估高德/騰訊/Leaflet 等替代方案,並善用 navigator.geolocation.watchPosition 實現即時追蹤功能。