百度地圖api,定位,新增城市控制元件,單擊獲得經緯度並mark
阿新 • • 發佈:2019-01-10
<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=13hKkYUjCLhkhnRlidP7Bmor"></script> <title>單擊獲取點選的經緯度</title> </head> <body> <div id="allmap" style="width:800px;height:600px;"></div> </body> </html> <script type="text/javascript"> // 百度地圖API功能 var map = new BMap.Map("allmap"); var mk; map.centerAndZoom("廣州", 12); map.enableScrollWheelZoom(); //啟用滾輪放大縮小,預設禁用 map.enableContinuousZoom(); //啟用地圖慣性拖拽,預設禁用 map.enableInertialDragging(); //新增選擇城市的控制元件 var size = new BMap.Size(50, 20); map.addControl(new BMap.CityListControl({ anchor: BMAP_ANCHOR_TOP_RIGHT, offset: size, // 切換城市之間事件 // onChangeBefore: function(){ // alert('before'); // }, // 切換城市之後事件 // onChangeAfter:function(){ // alert('after'); // } })); //單擊獲取點選的經緯度 map.addEventListener("click", function (e) { //alert(e.point.lng + "," + e.point.lat); map.removeOverlay(mk); mk = new BMap.Marker(e.point); map.addOverlay(mk); }); // 新增帶有定位的導航控制元件 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>