-
根据需求仿zillow官网手动在地图上绘制选择区域,进行寻找房源。
-
操作,点击创建区域,地图上进行点击然后拖动鼠标,绘制曲线,鼠标放开,链接首尾坐标,形成封闭区域,点击删除区域,移除曲线。
效果图如下:
<!doctype html>
<html>
<head>
<meta charset="utf-8">
<meta http-equiv="X-UA-Compatible" content="IE=edge">
<meta name="viewport" content="initial-scale=1.0, user-scalable=no, width=device-width"> <style>
html,
body {
width: 100%;
height: 100%;
}
#container {
width: 100%;
height: 90%;
}
.btn-draw {
padding: 10px 6px;
background: aqua;
color: #000;
float: left;
margin: 10px 6px;
border-radius: 10px;
cursor: pointer;
}
</style>
<title>手动画圆 绘制与移除</title>
<link rel="stylesheet" href="https://a.amap.com/jsapi_demos/static/demo-center/css/demo-center.css" />
<script src="https://webapi.amap.com/maps?v=1.4.15&key=您的key&plugin=AMap.CircleEditor"></script>
<script src="https://a.amap.com/jsapi_demos/static/demo-center/js/demoutils.js"></script>
</head>
<body>
<div id="container"></div>
<div id="drawCircle" class="btn-draw">添加区域</div>
<div id="removeCircle" class="btn-draw">删除区域</div>
<script type="text/javascript">
var map = new AMap.Map("container", {
center: [116.433322, 39.900256],
zoom: 14
}); //地图对象
let start = null; //起点
let BezierCurve = null; //曲线对象
let BezierCurveArray = []; //曲线对象数组
let path = []; //路径
document.getElementById('drawCircle').addEventListener('click', drawCircle, false);
document.getElementById('removeCircle').addEventListener('click', removePath, false);
function drawCircle() {
map.on('mousedown', getMapKeyDown);
setDragStatus(false);
}
function getMapKeyDown(e) {
start = [e.lnglat.getLng(), e.lnglat.getLat()];
path.push(start);
setPath(path); //部分情况监控不到鼠标抬起事件,重新按下会设置起点所以需要禁止,导致无法封闭
map.off('mousedown', getMapKeyDown);
map.on('mousemove', getMapMove);
}
function getMapMove(e) {
path.push([e.lnglat.getLng(), e.lnglat.getLat()]);
setPath(path);
}
//移出路径
function removePath() {
BezierCurveArray.forEach((item, index) => {
map.remove(item);
})
}
//设置路径
function setPath(array) {
BezierCurve = new AMap.BezierCurve({
strokeColor: 'blue', //边线颜色
strokeOpacity: 0.8, //边线透明度
strokeWeight: 2, //边线宽度
fillOpacity: 0.4, //填充透明度
fillColor: '#1791fc', //填充颜色
path: array,
map: map
}) BezierCurve.setMap(map);
BezierCurveArray.push(BezierCurve);
BezierCurve.on('mouseup', function() {
map.off('mousemove', getMapMove);
path.push(start);
setPath(path);
map.setFitView([BezierCurve]) setDragStatus(true) path = [];
})
//遗留bug //
map.on('mouseup', function() { //
})
} //设置当前地图的拖拽状态
function setDragStatus(flag) {
if (map) {
map.setStatus({
dragEnable: flag
});
}
}
</script>
</body>
</html>