點選百度地圖新增標註並獲取當前地理名稱
阿新 • • 發佈:2018-12-30
html部分:
<div id="allmap"></div>
<style type="text/css"> body, html{width: 100%;height: 100%;overflow: hidden;margin:0;font-family:"微軟雅黑";} </style>
js部分:
<script defer type="text/javascript"> // 百度地圖API功能 var x=""; var y=""; var map = new BMap.Map("allmap"); varpoint = new BMap.Point(116.404, 39.915); map.centerAndZoom(point , 11); var marker = new BMap.Marker(point); // 建立標註 map.addOverlay(marker); // 將標註新增到地圖中 setTimeout(function(){ map.setZoom(14); }, 1000); //2秒後放大到14級 map.enableScrollWheelZoom(true); //縮放地圖 map.addEventListener("click", showInfo); function showInfo(e){ x=e.point.lng; //獲取滑鼠當前點選的經緯度 y=e.point.lat; if(x != "" && y != ""){ clearAll(); //清除地圖上存在的標註 var point = new BMap.Point(x,y); map.centerAndZoom(point); marker = new BMap.Marker(point); // 建立新的標註map.addOverlay(marker); //將標註新增到地圖上 }else{ map.centerAndZoom("北京", 12); }
var point = new BMap.Point(x,y); //獲取當前地理名稱 var gc = new BMap.Geocoder(); gc.getLocation(point, function(rs){ var addComp = rs.addressComponents; alert(addComp.province + ", " + addComp.city + ", " + addComp.district + ", " + addComp.street + ", " + addComp.streetNumber); });} function clearAll(e){ map.removeOverlay(marker); }</script>
樣式截圖: