代碼javascript
<!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 {width: 100%;height: 100%;margin:0;font-family:"微軟雅黑";} #allmap{width:100%;height:100%;} p{margin-left:5px; font-size:14px;} </style> <script type="text/javascript" src="http://api.map.baidu.com/api?v=2.0&ak=sSelQoVi2L3KofLo1HOobonW"></script> <title>添加定位相關控件</title> </head> <body> <div id="allmap"></div> </body> </html> <script type="text/javascript"> // 百度地圖API功能 var map = new BMap.Map("allmap"); map.centerAndZoom(new BMap.Point(116.404, 39.915), 11); // 添加帶有定位的導航控件 var navigationControl = new BMap.NavigationControl({ // 靠左上角位置 anchor: BMAP_ANCHOR_TOP_LEFT, // LARGE類型 type: BMAP_NAVIGATION_CONTROL_LARGE, // 啓用顯示定位 enableGeolocation: true // 會多出一個點 }); map.addControl(navigationControl); // 添加定位控件 var geolocationControl = new BMap.GeolocationControl(); geolocationControl.addEventListener("locationSuccess", function(e){ // 定位成功事件 var address = ''; address += e.addressComponent.province; address += e.addressComponent.city; address += e.addressComponent.district; address += e.addressComponent.street; address += e.addressComponent.streetNumber; alert("當前定位地址爲:" + address); }); geolocationControl.addEventListener("locationError",function(e){ // 定位失敗事件 alert(e.message); }); map.addControl(geolocationControl); </script>
效果css