百度地圖的定位以及拖拽(顯示座標位置)
阿新 • • 發佈:2019-02-07
截圖示例
<!doctype html>
<html lang="en"><head>
<meta charset="UTF-8">
<meta name="Generator" content="EditPlus®">
<meta name="Author" content="">
<meta name="Keywords" content="">
<meta name="Description" content="">
<title></title>
<style type="text/css">
html{height:100%}
body{height:100%;margin:0px;padding:0px}
#map_canvas{
margin:0 auto;
border:2px solid #f9f7f6;
width:80%;
height:80%;
}
</style>
</head>
<body>
<div id="map_canvas"></div>
<script src="jquery-2.1.4.min.js"></script>
<script src="http://api.map.baidu.com/api?v=2.0&ak=74af171e2b27ee021ed33e549a9d3fb9"></script>
<script type="text/javascript" src="http://api.map.baidu.com/library/TextIconOverlay/1.2/src/TextIconOverlay_min.js"></script>
<script type="text/javascript" src="http://api.map.baidu.com/library/MarkerClusterer/1.2/src/MarkerClusterer_min.js"></script>
<script type="text/javascript">
var map = new BMap.Map("map_canvas"); // 建立地圖例項
var initLat = 39.916527;
var initLng = 116.397128;
var point = new BMap.Point(initLng, initLat); // 建立點座標
map.centerAndZoom(point, 13); // 初始化地圖,設定中心點座標和地圖級別
//var marker = new BMap.Marker(point); // 建立標註
//map.addOverlay(marker); // 將標註新增到地圖中
map.enableScrollWheelZoom(); // 啟用滾輪放大縮小
map.addControl(new BMap.NavigationControl()); // 啟用放大縮小 尺
//獲取當前位置
var geolocation = new BMap.Geolocation();
geolocation.getCurrentPosition(function(r){
if(this.getStatus() == BMAP_STATUS_SUCCESS){
mk = new BMap.Marker(r.point);
mk.addEventListener("dragend", showInfo);
mk.enableDragging(); //可拖拽
getAddress(r.point);
map.addOverlay(mk);//把點新增到地圖上
map.panTo(r.point);
}else {
alert('failed'+this.getStatus());
}
});
//繫結Marker的拖拽事件
function showInfo(e){
var gc = new BMap.Geocoder();
gc.getLocation(e.point, function(rs){
var addComp = rs.addressComponents;
var address = addComp.province + addComp.city + addComp.district + addComp.street + addComp.streetNumber;//獲取地址
alert(address);
//畫圖 ---》顯示地址資訊
var label = new BMap.Label(address,{offset:new BMap.Size(20,-10)});
map.removeOverlay(mk.getLabel());//刪除之前的label
mk.setLabel(label);
//alert(e.point.lng + ", " + e.point.lat + ", "+address);
});
}
//獲取地址資訊,設定地址label
function getAddress(point){
var gc = new BMap.Geocoder();
gc.getLocation(point, function(rs){
var addComp = rs.addressComponents;
var address = addComp.province + addComp.city + addComp.district + addComp.street + addComp.streetNumber;//獲取地址
alert(address);
//畫圖 ---》顯示地址資訊
var label = new BMap.Label(address,{offset:new BMap.Size(20,-10)});
map.removeOverlay(mk.getLabel());//刪除之前的label
mk.setLabel(label);
});
}
</script>
</body>
</html>