HTML5網頁定位,並將位置繪在百度地圖上
阿新 • • 發佈:2019-02-10
執行效果:
實現程式碼:
<!DOCTYPE html> <html lang="en"> <head> <meta charset="UTF-8"> <title>HTML5定位</title> <meta name="viewport" content="width=device-width, initial-scale=1" /> <script type="text/javascript" src="http://lib.sinaapp.com/js/jquery/1.7.2/jquery.min.js"></script> <script type="text/javascript" src="http://api.map.baidu.com/api?v=2.0&ak=wqBXfIN3HkpM1AHKWujjCdsi"></script> <script type="text/javascript" src="http://developer.baidu.com/map/jsdemo/demo/convertor.js"></script> <style type="text/css"> * { margin: 0px; padding: 0px; } body { font: normal 100% Helvetica, Arial, sans-serif; text-align: center; height: 100%; overflow: hidden; } #allmap { width: 100%; height: 100%; position: absolute; } </style> </head> <body> <script type="text/javascript"> $(function () { // 單次位置請求執行的函式 function getLocation() { if (navigator.geolocation) { navigator.geolocation.getCurrentPosition(showPosition, locationError); } else { alert("你的瀏覽器不支援 GeoLocation."); } } // 頁面載入時執行getLocation函式 //window.onload = getLocation; $("#btn").click(function () { getLocation(); }); getLocation(); }); //定位成功時,執行的函式 function showPosition(position) { var lon = position.coords.longitude; var lat = position.coords.latitude; // alert("您位置的經度是:"+lon+" 緯度是:"+lat); var map = new BMap.Map("allmap"); var point = new BMap.Point("" + lon + "", "" + lat + ""); map.centerAndZoom(point, 19); var gc = new BMap.Geocoder(); translateCallback = function (point) { var marker = new BMap.Marker(point); map.addOverlay(marker); map.setCenter(point); gc.getLocation(point, function (rs) { var addComp = rs.addressComponents; if (addComp.province !== addComp.city) { var sContent = "<div><h4 style='margin:0 0 5px 0;padding:0.2em 0'>你當前的位置是:</h4>" + "<p style='margin:0;line-height:1.5;font-size:13px;text-indent:2em'>" + addComp.province + ", " + addComp.city + ", " + addComp.district + ", " + addComp.street + ", " + addComp.streetNumber + "</p>" + "</div>"; } else { var sContent = "<div><h4 style='margin:0 0 5px 0;padding:0.2em 0'>你當前的位置是:</h4>" + "<p style='margin:0;line-height:1.5;font-size:13px;text-indent:2em'>" + addComp.city + ", " + addComp.district + ", " + addComp.street + ", " + addComp.streetNumber + "</p>" + "</div>"; } var infoWindow = new BMap.InfoWindow(sContent); map.openInfoWindow(infoWindow, point); }); } BMap.Convertor.translate(point, 0, translateCallback); } // 定位失敗時,執行的函式 function locationError(error) { switch (error.code) { case error.PERMISSION_DENIED: alert("User denied the request for Geolocation."); break; case error.POSITION_UNAVAILABLE: alert("Location information is unavailable."); break; case error.TIMEOUT: alert("The request to get user location timed out."); break; case error.UNKNOWN_ERROR: alert("An unknown error occurred."); break; } } </script> <input type="button" value="網頁定位-獲取我的位置" id="btn" style="padding: 10px 20px; font-size: 120%; margin: 20px;" /> <div id="allmap"> </div> </body> </html>