1. 程式人生 > >使用瀏覽器自帶定位功能初始化百度地圖

使用瀏覽器自帶定位功能初始化百度地圖

if(navigator.geolocation) { navigator.geolocation.getCurrentPosition(showPosition, showError); // HTML5獲取GPS裝置地理位置資訊 } else { document.getElementById("allmap").innerHTML = "Geolocation is not supported by this browser."; } function showPosition(position) { var
y = position.coords.latitude; // 獲取經度 var x = position.coords.longitude; // 獲取緯度 initMap(x, y); } // HTML5獲取地理位置資訊錯誤處理 function showError(error) { switch(error.code) { case error.PERMISSION_DENIED: document.getElementById("allmap").innerHTML = "User denied the request for Geolocation."
break; case error.POSITION_UNAVAILABLE: document.getElementById("allmap").innerHTML = "Location information is unavailable." break; case error.TIMEOUT: document.getElementById("allmap").innerHTML = "The request to get user location timed out."
break; case error.UNKNOWN_ERROR: document.getElementById("allmap").innerHTML = "An unknown error occurred." break; } } function initMap(x, y) { // 百度地圖API功能 //GPS座標 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); }