1. 程式人生 > >百度地圖 座標偏移、覆蓋物偏移解決方案

百度地圖 座標偏移、覆蓋物偏移解決方案

百度地圖定位不準確,這個問題困擾我一整天,想來度娘是強大的,各種查詢總於找到解決方案,其實就是將經緯度轉換為百度地圖識別的經緯度,是不是很扯。

網址

http://developer.baidu.com/map/jsdemo/demo/convertor.js     這是單個座標轉換介面

http://developer.baidu.com/map/jsdemo/demo/changeMore.js   這是批量轉換介面

1,單個轉換函式

//2011-7-25  
(function(){        //閉包  
function load_script(xyUrl, callback){  
    var head = document.getElementsByTagName('head')[0];  
    var script = document.createElement('script');  
    script.type = 'text/javascript';  
    script.src = xyUrl;  
    //借鑑了jQuery的script跨域方法  
    script.onload = script.onreadystatechange = function(){  
        if((!this.readyState || this.readyState === "loaded" || this.readyState === "complete")){  
            callback && callback();  
            // Handle memory leak in IE  
            script.onload = script.onreadystatechange = null;  
            if ( head && script.parentNode ) {  
                head.removeChild( script );  
            }  
        }  
    };  
    // Use insertBefore instead of appendChild  to circumvent an IE6 bug.  
    head.insertBefore( script, head.firstChild );  
}  
function translate(point,type,callback){  
    var callbackName = 'cbk_' + Math.round(Math.random() * 10000);    //隨機函式名  
    var xyUrl = "http://api.map.baidu.com/ag/coord/convert?from="+ type + "&to=4&x=" + point.lng + "&y=" + point.lat + "&callback=BMap.Convertor." + callbackName;  
    //動態建立script標籤  
    load_script(xyUrl);  
    BMap.Convertor[callbackName] = function(xyResult){  
        delete BMap.Convertor[callbackName];    //呼叫完需要刪除改函式  
        var point = new BMap.Point(xyResult.x, xyResult.y);  
        callback && callback(point);  
    }  
}  
  
window.BMap = window.BMap || {};  
BMap.Convertor = {};  
BMap.Convertor.translate = translate;  
})();  
2,批量轉換函式
//2011-7-25 zhangying  
(function(){  
function load_script(xyUrl, callback){  
    var head = document.getElementsByTagName('head')[0];  
    var script = document.createElement('script');  
    script.type = 'text/javascript';  
    script.src = xyUrl;  
    //借鑑了jQuery的script跨域方法  
    script.onload = script.onreadystatechange = function(){  
        if((!this.readyState || this.readyState === "loaded" || this.readyState === "complete")){  
            callback && callback();  
            // Handle memory leak in IE  
            script.onload = script.onreadystatechange = null;  
            if ( head && script.parentNode ) {  
                head.removeChild( script );  
            }  
        }  
    };  
    // Use insertBefore instead of appendChild  to circumvent an IE6 bug.  
    head.insertBefore( script, head.firstChild );  
}  
function transMore(points,type,callback){  
    var xyUrl = "http://api.map.baidu.com/ag/coord/convert?from=" + type + "&to=4&mode=1";  
    var xs = [];  
    var ys = [];  
    var maxCnt = 20;//每次傳送的最大個數  
    var send = function(){  
        var url = xyUrl + "&x=" + xs.join(",") + "&y=" + ys.join(",") + "&callback=callback";  
        //動態建立script標籤  
        load_script(url);  
        xs = [];  
        ys = [];  
    }  
    for(var index in points){  
        if(index % maxCnt == 0 && index != 0){  
            send();  
        }  
        xs.push(points[index].lng);  
        ys.push(points[index].lat);  
        if(index == points.length - 1){  
            send();  
        }  
    }  
      
}  
  
window.BMap = window.BMap || {};  
BMap.Convertor = {};  
BMap.Convertor.transMore = transMore;  
})();  

3,單個轉換函式與批量轉換函式 整合體
(function(){        //閉包  
function load_script(xyUrl, callback){  
    var head = document.getElementsByTagName('head')[0];  
    var script = document.createElement('script');  
    script.type = 'text/javascript';  
    script.src = xyUrl;  
    //借鑑了jQuery的script跨域方法  
    script.onload = script.onreadystatechange = function(){  
        if((!this.readyState || this.readyState === "loaded" || this.readyState === "complete")){  
            callback && callback();  
            // Handle memory leak in IE  
            script.onload = script.onreadystatechange = null;  
            if ( head && script.parentNode ) {  
                head.removeChild( script );  
            }  
        }  
    };  
    // Use insertBefore instead of appendChild  to circumvent an IE6 bug.  
    head.insertBefore( script, head.firstChild );  
}  
  
function translate(point,type,callback){//單個轉換  
    var callbackName = 'cbk_' + Math.round(Math.random() * 10000);    //隨機函式名  
    var xyUrl = "http://api.map.baidu.com/ag/coord/convert?from="+ type + "&to=4&x=" + point.lng + "&y=" + point.lat + "&callback=BMap.Convertor." + callbackName;  
    //動態建立script標籤  
    load_script(xyUrl);  
    BMap.Convertor[callbackName] = function(xyResult){  
        delete BMap.Convertor[callbackName];    //呼叫完需要刪除改函式  
        var point = new BMap.Point(xyResult.x, xyResult.y);  
        callback && callback(point);  
    };  
}  
  
function transMore(points,type,callback){//批量轉換  
    var xyUrl = "http://api.map.baidu.com/ag/coord/convert?from=" + type + "&to=4&mode=1";  
    var xs = [];  
    var ys = [];  
    var maxCnt = 30;//每次傳送的最大個數  
    var send = function(){  
        var url = xyUrl + "&x=" + xs.join(",") + "&y=" + ys.join(",") + "&callback=callback";  
        //動態建立script標籤  
        load_script(url);  
        xs = [];  
        ys = [];  
    };  
    for(var index in points){  
        if(index % maxCnt == 0 && index != 0){  
            send();  
        }  
        xs.push(points[index].lng);  
        ys.push(points[index].lat);  
        if(index == points.length - 1){  
            send();  
        }  
    }  
      
}  
  
window.BMap = window.BMap || {};  
BMap.Convertor = {};  
BMap.Convertor.translate = translate;  
BMap.Convertor.transMore = transMore;  
})(); 

另外附上兩個介面使用的示例原始碼

單個轉換的介面

[javascript] view plain copy
  1. <!DOCTYPE html>  
  2. <html>  
  3. <head>  
  4. <meta http-equiv="Content-Type" content="text/html; charset=utf-8" />  
  5. <meta name="viewport" content="initial-scale=1.0, user-scalable=no" />  
  6. <style type="text/css">  
  7. body, html,#allmap {width: 100%;height: 100%;overflow: hidden;margin:0;}  
  8. </style>  
  9. <script type="text/javascript" src="http://api.map.baidu.com/api?v=2.0&ak=您的金鑰"></script>  
  10. <script type="text/javascript" src="http://developer.baidu.com/map/jsdemo/demo/convertor.js"></script>  
  11. <title>GPS轉百度</title>  
  12. </head>  
  13. <body>  
  14. <div id="allmap"></div>  
  15. </body>  
  16. </html>  
  17. <script type="text/javascript">  
  18. // 百度地圖API功能
  19. //GPS座標
  20. var xx = 116.397428;  
  21. var yy = 39.90923;  
  22. var gpsPoint = new BMap.Point(xx,yy);  
  23. //地圖初始化
  24. var bm = new BMap.Map("allmap");  
  25. bm.centerAndZoom(gpsPoint, 15);  
  26. bm.addControl(new BMap.NavigationControl());  
  27. //新增谷歌marker和label
  28. var markergps = new BMap.Marker(gpsPoint);  
  29. bm.addOverlay(markergps); //新增GPS標註
  30. var labelgps = new BMap.Label("我是GPS標註哦",{offset:new BMap.Size(20,-10)});  
  31. markergps.setLabel(labelgps); //新增GPS標註
  32. //座標轉換完之後的回撥函式
  33. translateCallback = function (point){  
  34.     var marker = new BMap.Marker(point);  
  35.     bm.addOverlay(marker);  
  36.     var label = new BMap.Label("我是百度標註哦",{offset:new BMap.Size(20,-10)});  
  37.     marker.setLabel(label); //新增百度label
  38.     bm.setCenter(point);  
  39.     alert(point.lng + "," + point.lat);  
  40. }  
  41. setTimeout(function(){  
  42.     BMap.Convertor.translate(gpsPoint,0,translateCallback);     //真實經緯度轉成百度座標
  43. }, 2000);  
  44. </script>  


批量轉換的示例介面

[javascript] view plain copy
  1. <!DOCTYPE html>  
  2. <html>  
  3. <head>  
  4. <meta http-equiv="Content-Type" content="text/html; charset=utf-8" />  
  5. <meta name="viewport" content="initial-scale=1.0, user-scalable=no" />  
  6. <style type="text/css">  
  7. body, html,#allmap {width: 100%;height: 100%;overflow: hidden;margin:0;}  
  8. </style>  
  9. <script type="text/javascript" src="http://api.map.baidu.com/api?v=2.0&ak=您的金鑰"></script>  
  10. <script type="text/javascript" src="http://developer.baidu.com/map/jsdemo/demo/changeMore.js"></script>  
  11. <title>批量座標轉換</title>  
  12. </head>  
  13. <body>  
  14. <div id="allmap"></div>  
  15. </body>  
  16. </html>  
  17. <script type="text/javascript">  
  18. // 百度地圖API功能
  19. var map = new BMap.Map("allmap");  
  20. map.centerAndZoom(new BMap.Point(116.404, 39.915), 15);  
  21. var i;  
  22. var markers = [];  
  23. map.addEventListener("click",function(e){  
  24.     alert(e.point.lng + "," + e.point.lat);  
  25. });  
  26. //注意:百度和谷歌的經緯度座標順序是相反的。
  27. var points = [new BMap.Point(116.3786889372559,39.90762965106183),  
  28.               new BMap.Point(116.38632786853032,39.90795884517671),  
  29.               new BMap.Point(116.39534009082035,39.907432133833574),  
  30.               new BMap.Point(116.40624058825688,39.90789300648029),  
  31.               new BMap.Point(116.41413701159672,39.90795884517671)  
  32.              ];  
  33. function callback(xyResults){  
  34.  var xyResult = null;  
  35.  for(var index in xyResults){  
  36.   xyResult = xyResults[index];  
  37.   if(xyResult.error != 0){continue;}//出錯就直接返回;
  38.   var point = new BMap.Point(xyResult.x, xyResult.y);  
  39.      var marker = new BMap.Marker(point);  
  40.      map.addOverlay(marker);  
  41.      map.setCenter(point);// 由於寫了這句,每一個被設定的點都是中心點的過程
  42.     }  
  43. }  
  44. setTimeout(function(){  
  45.     BMap.Convertor.transMore(points,2,callback);        //一秒之後開始進行座標轉換。引數2,表示是從GCJ-02座標到百度座標。引數0,表示是從GPS到百度座標
  46. }, 1000);  
  47. </script>  
本文轉載地址:點選開啟連結