<!DOCTYPE html> <html> <head> <meta http-equiv="Content-Type" content="text/html; charset=utf-8" /> <meta name="viewport" content="initial-scale=1.0, user-scalable=no" /> <style type="text/css"> body, html,#allmap {width: 100%;height: 100%;overflow: hidden;margin:0;font-family:"微軟雅黑";} </style> <script type="text/javascript" src="http://api.map.baidu.com/api?v=2.0&ak=auwgLdjUcG605hhtQE4V5Srs"></script> <title>GPS轉百度</title> </head> <body> <div id="allmap"></div> </body> </html> <script type="text/javascript"> // 百度地圖API功能 //GPS座標 var x = 116.32715863448607; var y = 39.990912172420714; function getLocation() { if (navigator.geolocation) { navigator.geolocation.getCurrentPosition(showPosition); } else{ alert("該瀏覽器不支持獲取地理位置。");} } function showPosition(position) { var t="緯度: " + position.coords.latitude + "<br>經度: " + position.coords.longitude; x = position.coords.longitude; y = position.coords.latitude; var ggPoint = new BMap.Point(x,y); //地圖初始化 var bm = new BMap.Map("allmap"); bm.centerAndZoom(ggPoint, 15); bm.addControl(new BMap.NavigationControl()); //添加gps marker和label // var markergg = new BMap.Marker(ggPoint); // bm.addOverlay(markergg); //添加GPS marker // var labelgg = new BMap.Label("未轉換的GPS座標(錯誤)",{offset:new BMap.Size(20,-10)}); // markergg.setLabel(labelgg); //添加GPS label //座標轉換完以後的回調函數 translateCallback = function (data){ if(data.status === 0) { var marker = new BMap.Marker(data.points[0]); bm.addOverlay(marker); var label = new BMap.Label("轉換後的百度座標(正確)",{offset:new BMap.Size(20,-10)}); marker.setLabel(label); //添加百度label bm.setCenter(data.points[0]); } } setTimeout(function(){ var convertor = new BMap.Convertor(); var pointArr = []; pointArr.push(ggPoint); convertor.translate(pointArr, 1, 5, translateCallback) }, 1000); } getLocation(); </script>
執行效果:javascript
參考資料:css
http://blog.163.com/hongshaoguoguo@126/blog/static/1804698120149249044488/html
http://www.runoob.com/html/html5-geolocation.htmlhtml5