该篇文章两个知识点:
1.每次点击把手动添加的覆盖物存到自定义的数组,清除时再调用map.remove(传参),并把数组置空;
2.想自定义覆盖物样式:只需在callBackFn函数里,再添加content参数,里面可以添加我们自定义的标签名和样式,这样就算你想在里面画花都行了;
效果图:
dome:
<!DOCTYPE html>
<html>
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0, minimum-scale=1.0, maximum-scale=1.0, user-scalable=no,
minimal-ui"/>
<title></title>
<style>
html,body{width:100%;height:100%;}
#map{width:100%;height:100%;background: #ddd;}
#clear{position: fixed;bottom:5%;right:5%;padding:8px;color:#fff;font-size: 12px;background: #0792dd;}
.markerClass{background: url(local1.png);background-size: 100% 100%;width:52px;height:61px;}
</style>
<link rel="stylesheet" href="http://cache.amap.com/lbs/static/main1119.css"/>
<script type="text/javascript" src='http://webapi.amap.com/maps?v=1.4.2&key=你在高德申请的key&plugin=AMap.ToolBar'></script>
</head>
<body>
<div id="map"></div>
<span id="clear">点击清除覆盖物</span>
</body>
<script>
/*========设置中心点=======*/
var _lng = "113.2641077042";
var _lat = "23.1254620342";
var map = new AMap.Map('map', {
zoom: 15,
center: [_lng, _lat]
});
/*========设显示中心标注=======*/
var xbjMarker = new AMap.Marker({
position: [_lng, _lat]
});
xbjMarker.setMap(map);
xbjMarker.setLabel({
offset: new AMap.Pixel(-24, -26),
content: "地址展示框"
});
var addMarkers = [];
//添加覆盖物
var callBackFn = function(e) {
var marker = new AMap.Marker({
map: map,
position: [e.lnglat.getLng(), e.lnglat.getLat()],
content:'<div class="markerClass"></div>'//自定义覆盖物样式,可传可不传
});
addMarkers.push(marker);
};
//点击地图添加自定义覆盖物
map.on('click', callBackFn);
//点击清除按钮
document.getElementById("clear").addEventListener('click',function(){
map.remove(addMarkers);
addMarkers = [];
});
</script>
</html>