高德地图设置电子围栏
- 需求
- 效果图
- 代码实现
需求
给地图上人员锚点设置围栏区域,如果在此区域内则是在线状态,不在此区域内则是离线状态
效果图
双击可编辑或清除当前围栏
代码实现
前端实现区域框选:
//引入高德地图sdk"@amap/amap-jsapi-loader": "^1.0.1"
//html 展示操作按钮
<el-button type="primary" class="sub-btn" @click="handleStart">开始建围栏</el-button> //点击开始建立围栏后,围栏操作按钮才可见<div class="map-paint-box2" v-show="clickBox"><el-button plain @click="startWrite">开始绘制</el-button><el-button plain @click="clearWrite">清除</el-button><el-button plain @click="finishWrite">完成绘制</el-button>
</div>
//初始化地图:
function initMap() {AMapLoader.load({key:"", // 申请好的Web端开发者Key,首次调用 load 时必填version:"2.0", // 指定要加载的 JSAPI 的版本,缺省时默认1.4.15AMapUI: {version: '1.1',plugins:['control/BasicControl']} // 需要使用的的插件列表,如比例尺'AMap.Scale'等}).then((AMap)=>{map.value = new AMap.Map("container",{ //设置地图容器idresizeEnable: true, //是否监控地图容器尺寸变化zoom: 16, //初始化地图层级、center: [104.560920999, 31.4560470000]});}).catch(e=>{console.log(e);})
}
//初始化围栏信息
function handleStart() {allPoly = []//先从后端获取已经建立的围栏,展示在地图上存到currentOrgWeilanclickBox.value = true //展示操作按钮AMapLoader.load({key:"", // 申请好的Web端开发者Key,首次调用 load 时必填version:"2.0",plugins:['AMap.PolygonEditor','AMap.Polygon'], // 需要使用的的插件列表,如比例尺'AMap.Scale'等}).then((AMap)=>{polyEditor = new AMap.PolygonEditor(map.value);if (currentOrgWeilan.length > 0) {// 复现该组织下的围栏数据for (let one of currentOrgWeilan ) {let path = []let arr = one.regionScope.split(',')for (var i of arr) {let itemLatLng = []let oneArr = i.split('_')itemLatLng.push(Number(oneArr[0]), Number(oneArr[1]))path.push(itemLatLng)}//围栏数据处理 并展示var polygon = new AMap.Polygon({path: path})allPoly.push(polygon)}map.value.add(allPoly)map.value.setFitView(allPoly);polyEditor.addAdsorbPolygons(allPoly)for (let one of allPoly) {// 双击某个围栏可以进行编辑one.on('dblclick', () => {polyOverlays = []currentPoly = onepolyEditor.setTarget(one);polyOverlays.push(one)polyEditor.open();})}}// 直接在地图建立新的围栏polyEditor.on('add', function (data:any) {var polygon = data.target;polyEditor.addAdsorbPolygons(polygon);polyOverlays = []polyOverlays.push(polygon)allPoly.push(polygon)currentPoly = polygon // currentPoly 存放当前双击围栏,不然点其他操作时总是会操作到最后创建的围栏polygon.on('dblclick', () => {polyOverlays = []currentPoly = polygonpolyEditor.setTarget(polygon);polyOverlays.push(polygon)polyEditor.open();})})}).catch(e=>{console.log(e);})}
function startWrite() {polyEditor.close();polyEditor.setTarget();polyEditor.open();polyPointArr = []
}
function clearWrite() {allPoly.some((one,index)=> {if (one==currentPoly) {allPoly.splice(index,1)return true}})map.value.remove(polyOverlays)polyEditor.close()
}async function finishWrite() {polyEditor.close()for (var item of allPoly) {let polyAr = item.getPath()let str = '',allStrArr = [], allStr=''for (var one of polyAr) {str = one.lng+'_'+one.latallStrArr.push(str)}allStr=allStrArr.join(',');polyPointArr.push(allStr)}//polyPointArr是围栏角坐标集合,可以传给后端判断是否在坐标围栏内
}