萬盛學電腦網

您现在的位置: 萬盛學電腦網 >> 程式設計 >  >> 腳本程式專題 >> JavaScript

JavaScript 結合百度地圖 API 與 HTML5 Geolocation 獲取瀏覽器精確地理位置

核心 API:HTML5 Geolocation

// 檢查支援度
if (navigator.geolocation) {
    // 取得目前位置 (非同步)
    navigator.geolocation.getCurrentPosition(successCallback, errorCallback, options);
    
    // 持續監看位置變化 (行動裝置適用)
    var watchId = navigator.geolocation.watchPosition(successCallback, errorCallback, options);
    // 停止監看
    navigator.geolocation.clearWatch(watchId);
} else {
    alert('瀏覽器不支援地理定位');
}

參數詳解

  • successCallback(position):position.coords 包含 latitude, longitude, accuracy (精度米), altitude, heading, speed。
  • errorCallback(error):error.code (1:PERMISSION_DENIED, 2:POSITION_UNAVAILABLE, 3:TIMEOUT), error.message。
  • options:{ enableHighAccuracy: true, timeout: 10000, maximumAge: 0 }。

百度地圖 API 整合:經緯度 → 詳細地址 (逆地理編碼)

<!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>

關鍵技術細節

  1. 坐標系轉換:HTML5 Geolocation 回傳 **WGS84 (GPS) 座標**。百度地圖使用 **BD09** 坐標系。必須用 BMap.Convertor().translate(points, 1, 5, callback) 轉換 (1=GPS→BD09, 5=GCJ02→BD09),否則標記位置會偏移數百米。
  2. HTTPS 必須:Chrome 50+ 要求**安全上下文 (HTTPS 或 localhost)** 才允許使用 Geolocation API。HTTP 環境直接失敗 (PERMISSION_DENIED)。
  3. 使用者授權:首次會彈出許可對話框,使用者可拒絕。需優雅處理拒絕情況 (提示手動輸入地址、IP 定位備援)。
  4. 精度與耗電:enableHighAccuracy: true 使用 GPS (精度 ~10m,耗電、慢);false 使用 Wi-Fi/基地台/IP (精度 ~100-1000m,快、省電)。
  5. AK (Access Key):百度地圖 API 需申請 AK,配置白名單 (域名/IP),否則地圖無法載入。

IP 定位備援方案 (無授權/無 GPS 時)

// 百度 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();
}

現代替代:原生地圖 API 比較

服務商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 實現即時追蹤功能。

copyright © 萬盛學電腦網 all rights reserved