首先要註冊百度地圖API。javascript
註冊帳號,完善信息,點擊網站右上角的「API控制檯」,點擊,建立應用。html
應用類型選擇:「瀏覽器端」,應用服務全選,Referer白名單:*java
點擊提交。會生成一個訪問應用(AK)。api
AK碼記下來,後面頁面中要用它來引出百度地圖。瀏覽器
<!DOCTYPE html> <html> <head> <meta charset="utf-8"> <title></title <!-- 將百度地圖API引入,設置好本身的key --> <script type="text/javascript" src="http://api.map.baidu.com/api?v=2.0&ak=剛纔建立應用的AK"></script> </head> <body> <label >緯度:</label> <input type="text" id="lat" value="" readonly>
<label>經度:</label> <input type="text" id="lng" value="" readonly>
<label>地址 :</label> <input type="text" id="address" readonly> <button type="button" id="open"> 點擊顯示地圖獲取地址經緯度 </button> <div id='allmap' style='width: 60%; height: 60%; position: absolute; display: none'></div> </body> </html>
<script type="text/javascript"> document.getElementById('open').onclick = function () { if (document.getElementById('allmap').style.display == 'none') { document.getElementById('allmap').style.display = 'block'; } else { document.getElementById('allmap').style.display = 'none'; } } var map = new BMap.Map("allmap"); var geoc = new BMap.Geocoder(); //地址解析對象 var markersArray = []; var geolocation = new BMap.Geolocation(); var point = new BMap.Point(116.404412, 39.914714); map.centerAndZoom(point, 12); // 中心點 geolocation.getCurrentPosition(function (r) { if (this.getStatus() == BMAP_STATUS_SUCCESS) { var mk = new BMap.Marker(r.point); map.addOverlay(mk); map.panTo(r.point); map.enableScrollWheelZoom(true); } else { alert('failed' + this.getStatus()); } }, {enableHighAccuracy: true}) map.addEventListener("click", showInfo); //清除標識 function clearOverlays() { if (markersArray) { for (i in markersArray) { map.removeOverlay(markersArray[i]) } } } //地圖上標註 function addMarker(point) { var marker = new BMap.Marker(point); markersArray.push(marker); clearOverlays(); map.addOverlay(marker); } //點擊地圖時間處理 function showInfo(e) { document.getElementById('lng').value = e.point.lng; document.getElementById('lat').value = e.point.lat; geoc.getLocation(e.point, function (rs) { var addComp = rs.addressComponents; var address = addComp.province + addComp.city + addComp.district + addComp.street + addComp.streetNumber; if (confirm("肯定要地址是" + address + "?")) { document.getElementById('allmap').style.display = 'none'; document.getElementById('address').value = address; } }); addMarker(e.point); } </script>