(1)定义工具栏,添加到地图指定位置
var draw = new MapboxDraw({
displayControlsDefault: false,
controls: {
line_string: true, //画线图标
polygon: true, //画矩形图标
trash: true //清除工具
}
});
map.addControl(draw,'top-right');
(2)添加工具栏绘制监听
map.on('draw.create', measureDistance); //创建画线
map.on('draw.delete', removeMsg); //点击清除工具
(3)创建画线方法
var serviceUrl = host + "/iserver/services/map-world/rest/maps/World/"; //服务的url
//监听画线的方法
function measureDistance(e) {
if (!e.features) {
widgets.alert.showAlert(resources.msg_noDataRedraw, false);
}
var drawLine = e.features[0]; //包含画线的类型、画线点的金纬度坐标等信息
var param = new SuperMap.MeasureParameters(drawLine);
if(drawLine.geometry.type == "LineString"){ //当前为画线,使用请求距离的方法(measureDistance)
new mapboxgl.supermap.MeasureService(serviceUrl).measureDistance(param, function (serviceResult) {
var distance = serviceResult.result.distance;//获取返回的距离
var rounded_distance = Math.round(distance * 100) / 100;
widgets.alert.showAlert("点距="+rounded_distance + resources.msg_m, true); //此方法为引入的Js文件中定义
});
}else if(drawLine.geometry.type == "Polygon"){ //当前为画形状(使用画线的类型来判断),使用请求面积的方法来计算
new mapboxgl.supermap.MeasureService(serviceUrl).measureArea(param, function (serviceResult) {
var area = serviceResult.result.area; //获取返回的面积
var rounded_area = Math.round(area * 100) / 100;
widgets.alert.showAlert("圈中的面积="+rounded_area + resources.msg_sqm, true);
});
}
}
(4)点击清除工具(tagIdArray为手动添加的地图sourceid和layerid)
function removeMsg() {
for(var i = 0;i < tagIdArray.length;i++){
var existLayer = map.getLayer(tagIdArray[i]); //(根据id查询)layer存在则移除
if(existLayer){
map.removeLayer(tagIdArray[i]);
}
var existSource = map.getSource(tagIdArray[i]);//(根据id查询)资源存在则移除
if(existSource){
map.removeSource(tagIdArray[i]);
}
}
tagIdArray = [];
}