/** * 初始化函数 * @param {any} option 一个JSON类型 * selector 地图选择器 对应的DIV * onMapReady 地图加载完成调用 * onViewReady 地图加载完成后加载底图 * mapType 地图类型 '2d'或者'3d' 默认是'2d' * center 中心点 * extent 显示范围 * basemap 基础底图 */ function JTMapKit(option) { this.mapOption = {}; this._init(option || {}); //默认点符号 this.pointSymbol = { type: "simple-marker", style: "circle", color: "red", size: "10px", outline: { color: [255, 255, 0], width: 1 } } //起始点点符号 this.pointStrSymbol = { type: "simple-marker", style: "circle", color: "red", size: "10px", outline: { color: [255, 255, 0], width: 1 } } //终止点点符号 this.pointEndSymbol = { type: "simple-marker", style: "circle", color: "green", size: "10px", outline: { color: [255, 255, 0], width: 1 } } //中间点点符号 this.pointMiddleSymbol = { type: "simple-marker", style: "circle", color: [128, 128, 128], size: "10px", outline: { color: [255, 255, 0], width: 1 } } //默认线符号 this.lineSymbol = { type: "simple-line", color: [255, 255, 255], width: 2, cap: "round", join: "round" } //默认面符号 this.fillSymbol = { type: "simple-fill", color: [4, 90, 141, 0.3], style: "solid", outline: { color: [255, 255, 255], width: 2 } } //默认文字符号 this.textSymbol = { type: 'text', color: "#FFFFFF", haloColor: "#555555", haloSize: "2px", text: '', xoffset: 0, yoffset: 10, font: { size: 10, family: "Playfair Display", weight: "bold" } }; /* 草图编辑符号 点符号样式 */ this.sketchPointSymbol = { type: "simple-marker", style: "circle", color: [128, 128, 128], size: "10px", outline: { color: [255, 255, 0], width: 1 } } /* 草图编辑符号 面符号样式 */ this.sketchPolygonSymbol = { type: "simple-fill", color: [4, 90, 141, 0.3], style: "solid", outline: { type: "simple-line", color: [255, 255, 255], width: 1, style: 'short-dash-dot', cap: "round", join: "round" } } /* 草图编辑符号 现符号样式 */ this.sketchLineSymbol = { type: "simple-line", color: [255, 255, 255], width: 1, style: 'short-dash-dot', cap: "round", join: "round" } /* GPS图片符号 */ this.gpsSysmbol = { type: "picture-marker", url: this.serverUrl + 'icon_gps_cn.png', width: "40px", height: "40px", angle: 0, } this.isDrawing = false; //正在绘制中,用于控制多点绘制 /* 操作类型 */ this.actionType = { unknown: 'unknown', //未知 LandAnalysis: 'LandAnalysis', //地类分析 CaseAnalysis: 'CaseAnalysis', //案件占压分析 ForestAnalysis: 'ForestAnalysis', //林地占压分析 DiggingsAnalysis: 'DiggingsAnalysis', //矿区治理区占地分析 LayerQueryPoint: 'LayerQueryPoint', //点击查询图层数据 LayerQueryPolygon: 'LayerQueryPolygon', //区域查询图层数据 CommonSpatialAnalysis: 'CommonSpatialAnalysis', //通用空间占地分析 }; this.currentActionType = this.actionType.unknown; //当前操作类型 } /** * 原型中添加的方法 * @param {any} option */ JTMapKit.prototype.extend = function(option) { for (key in option) { JTMapKit.prototype[key] = option[key]; } } /**+++++++++++++++初始化相关内容+++++++++++++++++*/ JTMapKit.prototype.extend({ /** * 默认执行的初始化信息 * @param {any} option */ _init: function(option) { this.selector = option.selector || 'map'; //地图选择器 对应的DIV控件 this.serverUrl = option.serverUrl; this.onMapReady = option.onMapReady; //地图加载完后处理 this.onViewReady = option.onViewReady; //mapView加载完成后添加底图 this.onViewEventPointMove = option.onViewEventPointMove; //地图鼠标移动事件 this.onQueryTackEvent = option.onQueryTackEvent; //查询结果监听事件 this.onViewEventChange = option.onViewEventChange; //视图变化监听事件 this.onPrintEventProgress = option.onPrintEventProgress; //地图正在输出中 this.onPrintEventComplete = option.onPrintEventComplete; //地图输出完成事件 this.onEventError = option.onEventError; //错误事件接收 this.onCaseQueryPolygonBegin = option.onCaseQueryPolygonBegin; //区域查询方式查询案件开始监听 this.mapType = option.mapType || '2d'; //地图类型,2d,3d //小组件 this.uiZoom = null; //放大缩小组件 this.uiScaleBar = null; //比例尺组件 //地图相关参数 this.mapOption.basemap = option.basemap; //底图 this.mapOption.center = option.center; //中心点 this.mapOption.extent = option.extent; //全图 this.subDomains = ["t0", "t1", "t2", "t3", "t4", "t5", "t6", "t7"]; //天地图的URL服务器 //gov.cn this.baseMapVectorURL = "http://{subDomain}.tianditu.com/DataServer?T=vec_w&x={col}&y={row}&l={level}&tk=944815e0a333f538646868d896ef7378"; this.baseMapVectorLabelURL = "http://{subDomain}.tianditu.com/DataServer?T=cva_w&x={col}&y={row}&l={level}&tk=944815e0a333f538646868d896ef7378"; this.baseMapRasterURL = "http://{subDomain}.tianditu.com/DataServer?T=img_w&x={col}&y={row}&l={level}&tk=944815e0a333f538646868d896ef7378"; this.baseMapRasterLabelURL = "http://{subDomain}.tianditu.com/DataServer?T=cia_w&x={col}&y={row}&l={level}&tk=944815e0a333f538646868d896ef7378"; //绘图相关 this.draw = undefined; if (this.mapType.toLocaleLowerCase() === '3d') { } else { this._init2dMap(option); } }, /** * 创建tms格式的底图 * @param {String} baseMapUrl 底图服务地址 * @param {Function} callComplete 完成回调callComplete(baseLayer) */ _initBaseMapTMSLayer: function(baseMapUrl, callComplete) { if (!baseMapUrl && callComplete) callComplete(undefined); require(["esri/layers/BaseTileLayer"], function(BaseTileLayer) { /* 创建TMSLayer */ let TMSLayer = BaseTileLayer.createSubclass({ properties: { urlTemplate: null }, /* 获取切片地址 */ getTileUrl: function(z, y, x) { /* 这里对y轴瓦片编号进行转置 */ let y2 = Math.pow(2, z) - y - 1; return this.urlTemplate .replace("{z}", z) .replace("{x}", x) .replace("{y}", y2); }, }); /* 创建图层 */ let tmsLayer = new TMSLayer({ urlTemplate: baseMapUrl, title: '基础图层', }); /* 返回图层 */ if (callComplete) callComplete(tmsLayer); }); }, /** * 创建Mapbox格式的底图 * @param {String} baseMapUrl 底图服务地址 * @param {Function} callComplete 完成回调callComplete(baseLayer) */ _initBaseMapMapboxLayer(baseMapUrl, callComplete) { let _self = this; // require(["esri/layers/WebTileLayer"], function(WebTileLayer) { // let url = // "https://api.mapbox.com/styles/v1/chenchen1990/ckvgc14xrh7mo14qowdw4wrkf/tiles/512/{z}/{x}/{y}?access_token=pk.eyJ1IjoiY2hlbmNoZW4xOTkwIiwiYSI6ImNrbzA3eTY1OTA3dXkyd20zdG40ZGdmNXYifQ.xWKxjBG6mEDh55_oln0nAg"; // let mapboxLayer = new WebTileLayer(url, { // "subDomains": ["a", "b", "c"] // }); // if (callComplete) callComplete(mapboxLayer); // }); /* 新的方式添加底图 */ /* 此处注意使用TileLayer导致地图放到一定比例后无法放大 */ require(["esri/layers/MapImageLayer"], function(MapImageLayer) { var layer = new MapImageLayer({ url: 'https://map.geoq.cn/ArcGIS/rest/services/ChinaOnlineStreetPurplishBlue/MapServer', title: '基础底图', }); if (callComplete) callComplete(layer); }); }, /** * 初始化地图 * @param {JSON} option 配置项 */ _init2dMap: function(option) { console.log("地图控件开始初始化..."); var self = this; require(["esri/Map", "esri/views/MapView", "esri/core/urlUtils", "esri/layers/WMTSLayer", "esri/Basemap" ], function(Map, MapView, urlUtils, WMTSLayer, Basemap) { /* 创建底图 */ self._initBaseMapMapboxLayer(option.baseMapUrl, function(baseLayer) { console.log("创建的底图", baseLayer); if (baseLayer) { /* 创建底图 */ let baseMap = new Basemap({ baseLayers: [baseLayer], }); /* 挂接底图图层创建成功事件 */ baseLayer.on('layerview-create', function() { if (self.onViewReady) self.onViewReady(); }); /* 挂接底图图层创建失败事件 */ baseLayer.on('layerview-create-error', function(event) { if (self.onViewReady) self.onViewReady(); }); /* 创建地图实例 */ self.map = new Map({ basemap: baseMap, }); } else { if (self.onViewReady) self.onViewReady(); /* 创建地图实例 */ self.map = new Map(); } /* 创建地图视图实例 */ self.mapView = new MapView({ container: self.selector, map: self.map, }); /* 清空所有自带组件 */ self.mapView.ui.components = []; /* 禁止地图旋转 */ self.mapView.constraints = { rotationEnabled: false, // minScale: 10000, // maxZoom: 22, } /* 初始化加载的图层 */ if (!self.loadLayers) { self.loadLayers = []; } /* 注册底图事件 */ self._initRegisterMapEvent(); }); }); }, /** * 注册地图事件 */ _initRegisterMapEvent: function() { let _self = this; this.mapView.when(function() { /* 注册鼠标移动事件 */ _self.mapView.on("pointer-move", function(event) { if (self.onViewEventPointMove) { var mapPoint = self.mapView.toMap({ x: event.x, y: event.y }); //构建JSON var result = { sx: event.x.toFixed(3), sy: event.y.toFixed(3), mx: mapPoint.x.toFixed(3), my: mapPoint.y.toFixed(3) } self.onViewEventPointMove(result); } }); /* 注册地图拖动事件 */ _self.mapView.on("drag", function(event) { if (self.onViewEventChange) { self.onViewEventChange(self.mapView.extent); } }); /* 注册滚轮事件 */ _self.mapView.on("mouse-wheel", function(event) { //此处使用延时 主要是因为mouse-wheel事件是在滚轮刚开始滚动时就开始 //而不是在滚动结束时开始 window.setTimeout(function() { if (self.onViewEventChange) { self.onViewEventChange(self.mapView.extent); } }, 1000); }); /* 注册地图变化事件 */ _self.mapView.on("resize", function(event) { if (_self.onViewEventChange) { _self.onViewEventChange(_self.mapView.extent); } console.log('地图变化'); }); }); }, /** * 设置范围 * @param {any} extent */ setExtent: function(extent) { this.mapView.extent = extent; }, /** * 设置放大比例 * @param {any} zoom */ setZoom: function(zoom) { this.mapView.zoom = zoom; }, /** * 设置地图中心点 * @param {any} center */ setCenter: function(center) { this.mapView.center = center; }, /** * 设置比例尺 * @param {any} scale */ setScale: function(scale) { this.mapView.scale = scale; }, // 隐藏放大缩小的工具条 hidenZoomToolBar: function() { this.mapView.ui.remove("zoom"); }, /** 隐藏底部的LOGO */ hidenLogo: function() { this.mapView.ui.remove("attribution"); }, /** 放大 */ zoomIn: function() { var self = this; require(["esri/widgets/Zoom"], function(Zoom) { var zoom = new Zoom({ view: self.mapView }); zoom.zoomIn(); }); }, /** 缩小 */ zoomOut: function() { var self = this; require(["esri/widgets/Zoom"], function(Zoom) { var zoom = new Zoom({ view: self.mapView }); zoom.zoomOut(); }); }, /** * 定位地图中心位置 * @param {any} longitude 经度 * @param {any} latitude 纬度 */ zoomTo: function(longitude, latitude) { var self = this; require(["esri/geometry/SpatialReference", "esri/geometry/Extent" ], function(SpatialReference, Extent) { var spa = new SpatialReference({ wkid: 4326 }); var extent = new Extent({ xmin: parseFloat(longitude) - 0.002, ymin: parseFloat(latitude) - 0.002, xmax: parseFloat(longitude) + 0.002, ymax: parseFloat(latitude) + 0.002, spatialReference: spa }) self.mapView.extent = extent; }); }, /** * 缩放地图至指定区域 * @param {JSON} options 配置项 * xmin{double}:经度最小值 * ymin{double}:纬度最小值 * xmax{double}:经度最大值 * ymax{double}:纬度最大值 */ zoomToExtent: function(options) { var self = this; require(["esri/geometry/SpatialReference", "esri/geometry/Extent" ], function(SpatialReference, Extent) { var spa = new SpatialReference({ wkid: 4326 }); var extent = new Extent({ xmin: parseFloat(options.xmin), ymin: parseFloat(options.ymin), xmax: parseFloat(options.xmax), ymax: parseFloat(options.ymax), spatialReference: spa }) self.mapView.extent = extent; }); }, /** * 缩放地图至指定区域 * @param {JSON} options 配置项 * xmin{double}:经度最小值 * ymin{double}:纬度最小值 * xmax{double}:经度最大值 * ymax{double}:纬度最大值 */ zoomToExtentNormal: function(options) { let self = this; require(["esri/geometry/SpatialReference", "esri/geometry/Extent" ], function(SpatialReference, Extent) { let extent = new Extent({ xmin: parseFloat(options.xmin), ymin: parseFloat(options.ymin), xmax: parseFloat(options.xmax), ymax: parseFloat(options.ymax), spatialReference: self.mapView.spatialReference, }) self.mapView.extent = extent; }); }, }); /**++++++++++++++添加小组件++++++++++++++++++++*/ JTMapKit.prototype.extend({ /** * 添加放大缩小组件 */ setUIZoomVisible: function(isVisible) { var self = this; require(["esri/widgets/Zoom"], function(Zoom) { if (self.uiZoom == null) { self.uiZoom = new Zoom({ view: self.mapView, id: "toolsZoom" }); } var widget = self.mapView.ui.find("toolsZoom"); if (isVisible) { if (widget == undefined) { self.mapView.ui.add(self.uiZoom, { position: "top-left", }); } } else { if (widget != undefined) { self.mapView.ui.remove(self.uiZoom); } } }); }, /** * 添加放大缩小组件 */ setUIScaleBarVisible: function(isVisible) { var self = this; require(["esri/widgets/ScaleBar"], function(ScaleBar) { if (self.uiScaleBar == null) { self.uiScaleBar = new ScaleBar({ view: self.mapView, id: "toolsScaleBar", unit: "metric", }); } var widget = self.mapView.ui.find("toolsScaleBar"); if (isVisible) { if (widget == undefined) { self.mapView.ui.add(self.uiScaleBar, { position: "bottom-right", }); } } else { if (widget != undefined) { self.mapView.ui.remove(self.uiScaleBar); } } }); }, }); /**+++++++++++++++添加加载图层的相关内容+++++++++*/ JTMapKit.prototype.extend({ /** * 添加到图层中 * @param {any} id 图层ID 如果时服务图层 则代表子图层的索引Index * @param {any} title 图层的名称 * @param {any} visible 图层是否可见 * @param {any} type 图层的类型 * @param {any} slayer 所属服务图层 */ _addLayerToLayers: function(id, title, visible, type, slayer) { var self = this; self.loadLayers.push({ id: id, title: title, visible: visible, type: type, slayer: slayer }); }, /** * 添加动态服务图层 * @param {JSON} options 配置项 * options.url{string}:服务地址 * options.title{string}:图层标题 * options.subids{array}:子图层id集合 * options.visible{boolean}:图层是否显示 * @param {function} callSuccess 成功回调 * @param {function} callError 错误回调 */ addDynamicLayer: function(options, callSuccess, callError) { if (!options) return; /* 对子图层进行设置 */ if (!options.subids || !options.subids.length) return; let sublayers = []; for (let subid of options.subids) { sublayers.push({ id: subid, definitionExpression: options.filter == undefined ? "" : options .filter, }) } let _self = this; require(["esri/layers/MapImageLayer"], function(MapImageLayer) { var layer = new MapImageLayer({ url: options.url, title: options.title, sublayers: sublayers, visible: options.visible == undefined ? false : options .visible, }); /* 添加成功加载监听 */ layer.on("layerview-create", function() { layer.sublayers.find(function(subLayer) { subLayer.labelsVisible = options .labelVisible === undefined ? false : options.labelVisible; }) /* 设置子图层 */ if (callSuccess) callSuccess(); }); /* 添加添加错误监听 */ layer.on("layerview-create-error", function(event) { if (callError) callError(event.error.message); }); _self.map.add(layer, 1); }); }, /** * 添加发布的切片服务 * @param {JSON} options 配置项 * options.url{string}:服务地址 * options.title{string}:图层标题 * @param {function} callSuccess 成功回调 * @param {function} callError 错误回调 */ addTileLayer: function(options, callSuccess, callError) { if (!options) { return } let _self = this; require(["esri/layers/TileLayer"], function(TileLayer) { var layer = new TileLayer({ url: options.url, title: options.title, }); /* 添加创建成功回调 */ layer.on("layerview-create", function() { if (callSuccess) callSuccess(); }); layer.on("layerview-create-error", function(event) { if (callError) callError(event.error.message); }); _self.map.add(layer, 0); }); }, /** * 添加WMS服务图层 * @param {any} option 地图选项 * @param {any} index 地图图层索引 */ addWebTitleLayer: function(option, index, name, callback) { if (!option) { return; } var self = this; require(["esri/layers/WebTileLayer"], function(WebTileLayer) { var layer = new WebTileLayer(option); layer.title = name; //添加图层到视图中执行该代码 layer.on("layerview-create", function() { //将该图层添加到图层中 self._addLayerToLayers(layer.id, layer.title, layer .visible, "webtilelayer", undefined); if (callback) { callback(); } }); layer.on("layerview-create-error", function(event) { alert(event.error.message); }); self.map.add(layer, index); return layer; }); }, /** * 加载底图 * @param {Object} callback 加载完成后回调 */ loadBaseMap: function(callback) { var self = this; //添加天地图的影像图 回调后添加其他图层 主要时为了保证能够正常获取地图视图的坐标系 self.addWebTitleLayer({ urlTemplate: self.baseMapRasterURL, subDomains: self.subDomains, }, 0, "天地图影像图", function() { //添加天地图的标注图 self.addWebTitleLayer({ urlTemplate: self.baseMapRasterLabelURL, subDomains: self.subDomains, }, 100, "天地图标注", function() { callback(); }); }); }, /** * 切换底图为影像底图 * @param {Object} callback 加载完成回调 */ loadBaseRasterMap: function(callback) { var self = this; self.map.layers.removeAt(0); self.map.layers.removeAt(100); //添加天地图的影像图 回调后添加其他图层 主要时为了保证能够正常获取地图视图的坐标系 self.addWebTitleLayer({ urlTemplate: self.baseMapRasterURL, subDomains: self.subDomains, }, 0, "天地图影像图", function() { //添加天地图的标注图 self.addWebTitleLayer({ urlTemplate: self.baseMapRasterLabelURL, subDomains: self.subDomains, }, 100, "天地图标注", function() { callback(); }); }); }, /** * 切换底图为标准底图 * @param {Object} callback 加载完成回调 */ loadBaseVectorMap: function(callback) { var self = this; self.map.layers.removeAt(0); self.map.layers.removeAt(100); //添加天地图的影像图 回调后添加其他图层 主要时为了保证能够正常获取地图视图的坐标系 self.addWebTitleLayer({ urlTemplate: self.baseMapVectorURL, subDomains: self.subDomains, }, 0, "天地图影像图", function() { //添加天地图的标注图 self.addWebTitleLayer({ urlTemplate: self.baseMapVectorLabelURL, subDomains: self.subDomains, }, 100, "天地图标注", function() { callback(); }); }); }, /** * 获取加载的图层信息 * @param {Object} callback 获取完成回调 * callback([{title:},....]) */ getLayers: function(callback) { let _self = this; let resLayers = []; this.map.layers.forEach(function(layer, index) { resLayers.push({ title: layer.title, }); if (index === _self.map.layers.length - 1 && callback) { callback(resLayers); } }); }, }); /**+++++++++++++++草图编辑相关+++++++++++++++++++*/ JTMapKit.prototype.extend({ /** * 草图视图模型 * @param {function} callback 回调 */ _sketchViewModel: function(callback) { var self = this; require([ "esri/layers/GraphicsLayer", "esri/widgets/Sketch/SketchViewModel", "esri/geometry/projection", "esri/geometry/SpatialReference" ], function(GraphicsLayer, SketchViewModel, projection, SpatialReference) { /* 加入草图图层 */ if (!self.layerSketch) { self.layerSketch = new GraphicsLayer(); self.map.add(self.layerSketch); } /* 如果草图编辑工具已经初始化 则释放资源 重新初始化 */ if (self.sketchViewModel) { self.sketchViewModel.layer.graphics.removeAll(); self.sketchDrawGeometry = undefined; self.sketchViewModel.destroy(); self.sketchViewModel = null; } /* 创建草图编辑工具 */ if (!self.sketchViewModel) { self.sketchViewModel = new SketchViewModel({ layer: self.layerSketch, view: self.mapView, polygonSymbol: self.sketchPolygonSymbol, }); /* 绑定创建事件 */ self.sketchViewModel.on("create", function(event) { if (event.state == "start") { self.layerSketch.removeAll(); //删除全部 } /* 输出绘制要素 */ self._outGraphic(event, "创建"); }); /* 绑定redo事件 */ self.sketchViewModel.on('redo', function(event) { self._outGraphic(event, "恢复"); }); /* 绑定undo事件 */ self.sketchViewModel.on('undo', function(event) { self._outGraphic(event, "回退"); }); } /* 创建成功回调 */ if (callback) callback(); }); }, /** * 草图编辑过程中输出 * @param {Object} event 草图编辑事件 * @param {string} eventName 事件名称 */ _outGraphic: function(event, eventName) { /* 全局替换 */ let _self = this; /* 全局定义草图编辑绘制的要素 */ this.sketchDrawGeometry = undefined; /* 对绘制的草图要素进行赋值 */ if (event.graphic != undefined) { this.sketchDrawGeometry = event.graphic.geometry } /* 对绘制的草图要素进行赋值 */ if (event.graphics != undefined) { this.sketchDrawGeometry = event.graphics[0].geometry; } /* 输出回调 这很重要 */ if (this.onQueryPolygonComplete != undefined && this.sketchDrawGeometry != undefined && this .currentActionType == this.actionType.LayerQueryPolygon) { /* 多图层区域查询回调 */ if (event.type == 'create' && event.state == 'start') { this.onQueryPolygonComplete(0, this.sketchDrawGeometry); } else { this.onQueryPolygonComplete(this.sketchDrawGeometry.rings[0].length, this .sketchDrawGeometry); } } else if (this.onCommonSpatialAnalysisComplete != undefined && this .sketchDrawGeometry != undefined && this.currentActionType == this.actionType.CommonSpatialAnalysis ) { /* 通用空间占地分析回调 */ if (event.type == 'create' && event.state == 'start') { this._projectTransform({ geometry: this.sketchDrawGeometry, wkid: 4326, }, function(outGeometry) { _self.onCommonSpatialAnalysisComplete(0, outGeometry); }) } else { this._projectTransform({ geometry: this.sketchDrawGeometry, wkid: 4326, }, function(outGeometry) { _self.onCommonSpatialAnalysisComplete(outGeometry.rings[0] .length, outGeometry); }) } } }, /** * 坐标转换 * @param {JSON} options 配置项 * @param {function} callSuccess 转换成功回调 */ _projectTransform: function(options, callSuccess) { require([ "esri/geometry/projection", "esri/geometry/SpatialReference" ], function(projection, SpatialReference) { let outSpatialReference = new SpatialReference({ wkid: options.wkid, }); projection.load().then(function() { let outGeometry = projection.project(options.geometry, outSpatialReference); if (callSuccess) callSuccess(outGeometry); }) }); }, /** * 提取要素坐标 * @param {Object} geo 待提取的要素 * @param {Function} callback 提取完成回调 */ _pickCoordinate: function(geo, callback) { var resCoords = ""; if (geo.type == "point") { resCoords = point.x + "," + point.y; callback("point", resCoords); } else if (geo.type == "polyline") { for (var idx = 0; idx < geo.paths[0].length; idx++) { var point = geo.getPoint(0, idx); if (resCoords == "") { resCoords = point.x + "," + point.y; } else { resCoords += "," + point.x + "," + point.y; } } callback("polyline", resCoords); } else if (geo.type == "polygon") { for (var idx = 0; idx < geo.rings[0].length; idx++) { var point = geo.getPoint(0, idx); if (resCoords == "") { resCoords = point.x + "," + point.y; } else { resCoords += "," + point.x + "," + point.y; } } callback("polygon", resCoords); } else { callback(undefined, ""); } }, /** * 激活草图绘制面要素工具 */ sketchPolygonTools: function() { var self = this; this._sketchViewModel(function() { self.sketchViewModel.create("polygon", { mode: "click" }); }); }, /** * 草图恢复 */ sketchRedo: function() { if (this.sketchViewModel) { this.sketchViewModel.redo(); } }, /** * 草图回退 */ sketchUndo: function() { if (this.sketchViewModel) { this.sketchViewModel.undo(); } }, /** * 草图删除全部绘制 */ sketchDelete: function() { var self = this; this._sketchViewModel(function() { self.sketchViewModel.cancel(); self.layerSketch.removeAll(); //删除全部 }); }, /** * 获取全部绘制要素 * @param {function} callback 回调 */ sketchGraphic: function(callback) { var self = this; if (self.layerSketch) { if (self.layerSketch.graphics.length > 0) { self.layerSketch.graphics.filter(function(graphic) { self.sGraphic = graphic; require([ "esri/geometry/projection", "esri/geometry/SpatialReference", "esri/geometry/support/geodesicUtils" ], function(projection, SpatialReference, geodesicUtils) { //定义坐标系 var outSpatialReference = new SpatialReference({ wkid: 4326 }); //默认没有坐标系 需要设置 self.sGraphic.geometry.spatialReference = self .mapView .spatialReference; //必须这样执行 只有projection.load()执行完成才能调用坐标转换 projection.load().then(function() { var proGeometry = projection .project(self .sGraphic .geometry, outSpatialReference); self._pickCoordinate(proGeometry, function(type, result) { callback(type, result); }); }); }); }); } else { //如果没有绘制要素则返回undefined callback(0, undefined); } } else { callback(false, undefined); } }, /** * 添加绘制编辑要素 * @param {Object} graphic 要素 */ sketchAddGraphic: function(graphic) { var self = this; this._sketchViewModel(function() { require([ "esri/geometry/projection", "esri/geometry/SpatialReference", "esri/Graphic" ], function(projection, SpatialReference, Graphic) { //定义坐标系 var outSpatialReference = new SpatialReference({ wkid: 4326 }); graphic.spatialReference = outSpatialReference; //由于选择的图斑是WGS84坐标系下的成果 需要改正 projection.load().then(function() { self.layerSketch.removeAll(); var polygon = projection.project(graphic .geometry, self .mapView .spatialReference); var resGraphic = new Graphic({ geometry: polygon, symbol: self.sketchViewModel .polygonSymbol, }); self.layerSketch.add(resGraphic); }); }); }); }, }); /**+++++++++++++++绘制相关+++++++++++++++++++++++*/ JTMapKit.prototype.extend({ _draw: function(type, option) { var self = this; self.isDrawing = true; require([ "esri/views/draw/Draw", "esri/layers/GraphicsLayer", "esri/Graphic" ], function(Draw, GraphicsLayer, Graphic) { self.clearGraphic(); if (!self.graphicsLayer) { self.graphicsLayer = new GraphicsLayer(); self.map.layers.add(self.graphicsLayer); } var draw = new Draw({ view: self.mapView }); var action = draw.create(type); option.type = type; //添加点 action.on("vertex-add", function(evt) { self._drawActionHandler(evt, option, Graphic); }); //绘制结束 action.on("draw-complete", function(evt) { self.isDrawing = false; self._drawActionHandler(evt, option, Graphic); }); //删除点 action.on("vertex-remove", function(evt) { self._drawActionHandler(evt, option, Graphic); }); action.on("cursor-update", function(evt) { if (type === 'circle') { self._drawActionHandler(evt, option, Graphic); } else if (type === 'rectangle') { self._drawActionHandler(evt, option, Graphic); } }) if (type === 'multipoint') { self.mapView.on('click', function(evt) { self._addMultipoint(evt, option, Graphic) }) } }); }, //绘制处理事件 _drawActionHandler(evt, option, Graphic) { if (option.type === 'circle') { this._drawCircleActionHandler(evt, option, Graphic); return; } else if (option.type === 'rectangle') { this._drawRectangleActionHandler(evt, option, Graphic); return; } var geometry; if (evt.coordinates) { //绘制单个点时获取的是coordinates var coordinates = evt.coordinates; geometry = { type: "point", x: coordinates[0], y: coordinates[1], spatialReference: this.mapView.spatialReference }; } else if (evt.vertices) { var vertices = evt.vertices; var type = option.type; geometry = { spatialReference: this.mapView.spatialReference }; //多点 if (type === 'multipoint') { this.isDrawing = false; geometry.points = vertices; geometry.type = "multipoint"; } else if (type === 'polyline') { geometry.paths = vertices; geometry.type = "polyline"; } else { geometry.rings = vertices; geometry.type = "polygon"; } } var graphic = new Graphic({ geometry: geometry, symbol: option.symbol }); this.graphicsLayer.removeAll(); this.graphicsLayer.add(graphic); //将绘制的要素通过回调方法回调回去 if (this.onDrawEventComplete && !this.isDrawing) { //将绘制的图元要素返回 this.onDrawEventComplete(geometry); } }, //绘制圆 _drawCircleActionHandler(evt, option, Graphic) { var self = this; require(["esri/geometry/Circle", "esri/geometry/Point" ], function(Circle, Point) { var vertices = evt.vertices; if (vertices.length < 2) { return } self.graphicsLayer.removeAll(); var center = new Point({ hasZ: false, hasM: false, x: vertices[0][0], y: vertices[0][1], spatialReference: self.mapView.spatialReference }); var radius = center.distance(new Point({ hasZ: false, hasM: false, x: vertices[1][0], y: vertices[1][1], spatialReference: self.mapView.spatialReference })); var graphic = new Graphic({ geometry: new Circle({ hasZ: false, hasM: false, center: center, radius: radius, spatialReference: self.mapView.spatialReference }), symbol: option.symbol }); self.graphicsLayer.add(graphic); }); }, //绘制矩形 _drawRectangleActionHandler(evt, option, Graphic) { var self = this; require(["esri/geometry/Circle", "esri/geometry/Polygon" ], function(Circle, Polygon) { //获取所有顶点 var vertices = evt.vertices; if (vertices.length < 2) { return } var rings = [vertices[0], [vertices[0][0], vertices[1][1]], vertices[1], [vertices[1][0], vertices[0][1]] ]; self.graphicsLayer.removeAll(); var graphic = new Graphic({ geometry: new Polygon({ hasZ: false, hasM: false, rings: [rings], spatialReference: self.mapView.spatialReference }), symbol: option.symbol }); self.graphicsLayer.add(graphic); }); }, //绘制多个点 _addMultipoint: function(evt, option, Graphic) { if (this.isDrawing) { var graphic = new Graphic({ geometry: evt.mapPoint, symbol: option.symbol }); this.graphicsLayer.add(graphic); } }, //绘制单个点 drawPoint: function(option) { var options = option || {}; if (!options.symbol) { options.symbol = this.pointSymbol; } this._draw('point', options); }, //绘制多个点 drawMultiPoint: function(option) { this.isDrawing = true; var options = option || {}; if (!options.symbol) { options.symbol = this.pointSymbol; } this._draw('multipoint', options); }, //绘制线 drawPolyline: function(option) { var options = option || {}; if (!options.symbol) { options.symbol = this.lineSymbol; } this._draw('polyline', options); }, //绘制多边形 drawPolygon: function(option) { var options = option || {}; if (!options.symbol) { options.symbol = this.fillSymbol; } this._draw('polygon', options); }, //绘制矩形 drawRectangle: function(option) { var options = option || {}; if (!options.symbol) { options.symbol = this.fillSymbol; } this._draw('rectangle', options); }, //绘制圆 drawCircle: function(option) { var options = option || {}; if (!options.symbol) { options.symbol = this.fillSymbol; } this._draw('circle', options); }, //清空绘制图层 clearGraphic: function() { if (this.graphicsLayer) { this.graphicsLayer.removeAll(); } this.sketchDelete(); //删除编辑工具编辑内容 this.queryTaskGraphic = undefined; //初始化查询绘制要素 this.measureGraphic = undefined; //初始化测量绘制要素 if (this.draw) { this.draw.reset(); //清除全部动作 this.draw = undefined; } this.isDrawing = false; //重置测量标志 this.mapView.popup.visible = false; //关闭气泡窗口 } }) /**+++++++++++++++查询相关+++++++++++++++++++++++*/ JTMapKit.prototype.extend({ /** * 查询任务 * @param {Object} type 类型 * @param {Object} option 配置项 */ _queryTack: function(type, option) { var self = this; self.clearGraphic(); self.isDrawing = true; require([ "esri/views/draw/Draw", "esri/layers/GraphicsLayer", "esri/Graphic" ], function(Draw, GraphicsLayer, Graphic) { if (!self.graphicsLayer) { self.graphicsLayer = new GraphicsLayer(); self.map.layers.add(self.graphicsLayer); } if (!self.draw) { self.draw = draw = new Draw({ view: self.mapView, }); } else { self.draw.reset(); } var action = draw.create(type); action.mode = "click"; //只有点击绘制 option.type = type; //添加点 action.on("vertex-add", function(evt) { self._queryTackActionHandler(evt, option, Graphic); }); //绘制结束 action.on("draw-complete", function(evt) { self.isDrawing = false; self._queryTackActionHandler(evt, option, Graphic); }); action.on("cursor-update", function(evt) { if (type === 'rectangle') { self._queryTackRectangleActionHandler(evt, option, Graphic); } }) }); }, /** * @param {Object} evt 事件 * @param {JSON} option 配置项 * @param {Object} Graphic 要素 */ _queryTackActionHandler(evt, option, Graphic) { var self = this; //矩形查询绘制事件 if (option.type === 'rectangle') { this._queryTackRectangleActionHandler(evt, option, Graphic); return; } var geometry, clickPoint; if (evt.coordinates) { //绘制单个点时获取的是coordinates var coordinates = evt.coordinates; geometry = { type: "point", x: coordinates[0], y: coordinates[1], spatialReference: this.mapView.spatialReference }; } else if (evt.vertices) { var vertices = evt.vertices; //创建点击点 以便实现效果 clickPoint = { type: "point", x: vertices[vertices.length - 1][0], y: vertices[vertices.length - 1][1], spatialReference: this.mapView.spatialReference }; var type = option.type; geometry = { spatialReference: this.mapView.spatialReference }; if (type === 'polyline') { geometry.paths = vertices; geometry.type = "polyline"; } else { geometry.rings = vertices; geometry.type = "polygon"; } } //如果不存在则创建 否则更新 if (!this.queryTaskGraphic) { this.queryTaskGraphic = new Graphic({ geometry: geometry, symbol: option.symbol }); this.graphicsLayer.add(this.queryTaskGraphic); } else { this.queryTaskGraphic.geometry = geometry; } //追加点击点 var graphicPoint = new Graphic({ geometry: clickPoint, symbol: this.pointSymbol }); this.graphicsLayer.add(graphicPoint); var mGeometry = this.queryTaskGraphic.geometry; //获取绘制的要素 /* 判断查询方式 */ if (option.type === 'point') { self._queryTaskFromGeometry(self.queryTaskGraphic.geometry); self.queryTaskGraphic = undefined; } else if (option.type === 'polygon') { //绘制的是查询面 且点数大于等于3 if (mGeometry.type == 'polygon' && mGeometry.rings[0].length >= 3) { if (self.onCaseQueryPolygonBegin != undefined) { self.onCaseQueryPolygonBegin(); } } } }, /** * 显示测量结果 * @param {ESRIPoint} location 测量结果内容 * @param {function} callback 点击查询回调 */ _showQueryResultPopup: function(location, callback) { /* 创建查询按钮 */ var queryButton = document.createElement("button"); queryButton.className = "mui-btn mui-btn-primary mui-icon app-icon app-icon-map-areaquery wc-btn-child wc-btn-query"; var btnLabel = document.createTextNode("查询案件"); queryButton.appendChild(btnLabel); queryButton.onclick = function(event) { if (callback) callback(); } /* 显示弹窗试试 */ var popup = this.mapView.popup; /* 显示位置 */ popup.location = location; /* 设置标题 */ popup.title = "区域案件查询"; /* 设置显示内容 */ popup.viewModel.content = queryButton; /* 控制窗口的停靠按钮是否显示 */ popup.dockOptions = { buttonEnabled: false, } /* 控制是否显示关闭按钮 */ popup.visibleElements = { closeButton: true, featureNavigation: false } popup.on("trigger-action", function(event) { console.log("ActionId = " + event.action.id); }); /* 关闭自动缩放按钮 */ popup.viewModel.includeDefaultActions = false; /* 控制是否显示 */ popup.visible = true; }, //查询绘制矩形 _queryTackRectangleActionHandler(evt, option, Graphic) { var self = this; require(["esri/geometry/Circle", "esri/geometry/Polygon" ], function(Circle, Polygon) { //获取所有顶点 var vertices = evt.vertices; if (vertices.length < 2) { return } var rings = [vertices[0], [vertices[0][0], vertices[1][1]], vertices[1], [vertices[1][0], vertices[0][1]] ]; self.graphicsLayer.removeAll(); var graphic = new Graphic({ geometry: new Polygon({ hasZ: false, hasM: false, rings: [rings], spatialReference: self.mapView.spatialReference }), symbol: option.symbol }); self.graphicsLayer.removeAll(); self.graphicsLayer.add(graphic); //执行查询 if (!self.isDrawing) { self._queryTaskFromGeometry(graphic.geometry); } }); }, /** * 根据要素进行查询 * @param {Object} geometry 参考要素 */ _queryTaskFromGeometry: function(geometry) { var self = this; require([ "esri/tasks/support/Query", "esri/tasks/QueryTask", "esri/geometry/projection", "esri/geometry/SpatialReference" ], function(Query, QueryTask, projection, SpatialReference) { var qTask = new QueryTask({ url: self.queryURL }); var params = new Query({ returnGeometry: true, outFields: ["*"], distance: 2, geometry: geometry, spatialRelationship: "intersects", where: self.queryFilter, }); //定义坐标系 var outSpatialReference = new SpatialReference({ wkid: 4326 }); qTask.execute(params).then(function(response) { /* 打印当前查询类型 */ console.log("当前查询类型 = " + self.currentActionType); /* 如果当前为案件分析动作 且挂接了回调事件 */ if (self.onForestAnalysisEvent && self .currentActionType == self .actionType.ForestAnalysis) { self.graphicsLayer.removeAll(); //删除绘制的要素 if (response.features.length == 0) { self.onForestAnalysisEvent(undefined); } else { self.onForestAnalysisEvent(response.features[0] .attributes[ 'OBJECTID']); } } else if (self.onDiggingsAnalysisEvent && self .currentActionType == self .actionType.DiggingsAnalysis) { self.graphicsLayer.removeAll(); //删除绘制的要素 if (response.features.length == 0) { self.onDiggingsAnalysisEvent(undefined); } else { self.onDiggingsAnalysisEvent(response.features[ 0] .attributes[ 'OBJECTID']); } } else if (self.onQueryTackEvent) { self.graphicsLayer.removeAll(); //删除绘制的要素 //变换投影 projection.load().then(function() { //将最终的要素图形转换为经纬度返回 response.features.forEach(function( graphic, index) { graphic.geometry .spatialReference = self .mapView .spatialReference; var geo = projection .project(graphic .geometry, outSpatialReference ); graphic.geometry = geo; }); self.onQueryTackEvent(response .features); }); } /* 清除查询标志 */ self.currentActionType = self.actionType.unknown; }); } ); }, /** * 根据绘制要素执行查询任务 */ queryTaskFromGeometry: function() { this._queryTaskFromGeometry(this.queryTaskGraphic.geometry); this.queryTaskGraphic = undefined; }, /** * 点击查询 * @param {JSON} option */ queryTackPoint: function(option) { var options = option || {}; this.isDrawing = true; if (!options.symbol) { options.symbol = this.pointSymbol; } if (option.url) { this.queryURL = option.url; } if (option.filter) { this.queryFilter = option.filter; } this._queryTack('point', options); }, /** * 点图查询案件 * @param {url} option 配置项 * url{string}:查询图层访问地址 * filter{string}:查询图层过滤条件 * actionType{string}:动作类型 */ queryCase: function(option) { var options = option || {}; this.isDrawing = true; if (!options.symbol) { options.symbol = this.pointSymbol; } if (option.url) { this.queryURL = option.url; } if (option.filter) { this.queryFilter = option.filter; } /* 设置当前动作类型为案件查询 */ this.currentActionType = this.actionType.CaseAnalysis; this._queryTack('point', options); }, /** * 点图查询林地 * @param {url} option 配置项 * url{string}:查询图层访问地址 * filter{string}:查询图层过滤条件 * actionType{string}:动作类型 */ queryForest: function(option) { var options = option || {}; this.isDrawing = true; if (!options.symbol) { options.symbol = this.pointSymbol; } if (option.url) { this.queryURL = option.url; } if (option.filter) { this.queryFilter = option.filter; } /* 设置当前动作类型为案件查询 */ this.currentActionType = this.actionType.ForestAnalysis; this._queryTack('point', options); }, /** * 点图查询矿区治理区 * @param {url} option 配置项 * url{string}:查询图层访问地址 * filter{string}:查询图层过滤条件 * actionType{string}:动作类型 */ queryDiggingsAnalysis: function(option) { var options = option || {}; this.isDrawing = true; if (!options.symbol) { options.symbol = this.pointSymbol; } if (option.url) { this.queryURL = option.url; } if (option.filter) { this.queryFilter = option.filter; } /* 设置当前动作类型为案件查询 */ this.currentActionType = this.actionType.DiggingsAnalysis; this._queryTack('point', options); }, /** * @param {Object} option 多边形查询 */ queryTackPolygon: function(option) { var options = option || {}; this.isDrawing = true; if (!options.symbol) { options.symbol = this.fillSymbol; } if (option.url) { this.queryURL = option.url; } if (option.filter) { this.queryFilter = option.filter; } this._queryTack('polygon', options); }, /** * 矩形查询 * @param {JSON} option 配置项 */ queryTackRectangle: function(option) { var options = option || {}; this.isDrawing = true; if (!options.symbol) { options.symbol = this.fillSymbol; } if (option.url) { this.queryURL = option.url; } if (option.filter) { this.queryFilter = option.filter; } this._queryTack('rectangle', options); }, /** * 根据传入的参数查询图层数据 * @param {JSON} option 配置项 * type:{string} 类型 * url{string}:查询的服务地址 * filter{string}:过滤条件 * queryLayers{array}:查询图层数组 */ queryLayerByGeometry: function(option) { let _self = this; if (option.url) { this.queryURL = option.url; } if (option.filter) { this.queryFilter = option.filter; } if (option.queryLayers) { this.queryLayers = option.queryLayers; } require([ "esri/geometry/Polygon", "esri/geometry/Point", ], function(Polygon, Point) { let geometry = undefined; if (option.type === 'polygon') { geometry = new Polygon({ spatialReference: { wkid: option.geometry.spatialReference.wkid, }, rings: option.geometry.rings, }) } else if (option.type === 'point') { geometry = new Point({ spatialReference: { wkid: option.geometry.spatialReference.wkid, }, x: option.geometry.x, y: option.geometry.y, }) } if (geometry != undefined) { _self._queryLayersTaskFromGeometry(geometry); } }); }, /** * @param {string} type * @param {JSON} option 配置项 */ _queryLayersTack: function(type, option) { var self = this; /* 清除绘制的要素 */ self.clearGraphic(); /* 设置当前为绘制模式 */ self.isDrawing = true; require([ "esri/views/draw/Draw", "esri/layers/GraphicsLayer", "esri/Graphic" ], function(Draw, GraphicsLayer, Graphic) { /* 判断绘制要素的图层是否存在,如果不存在则创建 */ if (!self.graphicsLayer) { self.graphicsLayer = new GraphicsLayer(); self.map.layers.add(self.graphicsLayer); } /* 判断绘制是否启用,如果未启用,则创建,如果启用则重置 */ if (!self.draw) { self.draw = draw = new Draw({ view: self.mapView, }); } else { self.draw.reset(); } /* 创建绘制动作 */ let action = draw.create(type); action.mode = "click"; //只有点击绘制 option.type = type; /* 添加绘制点监听 */ action.on("vertex-add", function(evt) { self._queryLayersTackActionHandler(evt, option, Graphic); }); /* 添加绘制完成监听 */ action.on("draw-complete", function(evt) { self.isDrawing = false; self._queryLayersTackActionHandler(evt, option, Graphic); }); }); }, /** * @param {Object} evt 事件 * @param {JSON} option 配置项 * @param {Object} Graphic 要素 */ _queryLayersTackActionHandler(evt, option, Graphic) { let self = this; let geometry, clickPoint; if (evt.coordinates) { /* 绘制单个点时获取的是coordinates */ let coordinates = evt.coordinates; geometry = { type: "point", x: coordinates[0], y: coordinates[1], spatialReference: this.mapView.spatialReference }; } else if (evt.vertices) { var vertices = evt.vertices; clickPoint = { type: "point", x: vertices[vertices.length - 1][0], y: vertices[vertices.length - 1][1], spatialReference: this.mapView.spatialReference }; var type = option.type; geometry = { spatialReference: this.mapView.spatialReference }; if (type === 'polyline') { geometry.paths = vertices; geometry.type = "polyline"; } else { geometry.rings = vertices; geometry.type = "polygon"; } } //如果不存在则创建 否则更新 if (!this.queryTaskGraphic) { this.queryTaskGraphic = new Graphic({ geometry: geometry, symbol: option.symbol }); this.graphicsLayer.add(this.queryTaskGraphic); } else { this.queryTaskGraphic.geometry = geometry; } //追加点击点 var graphicPoint = new Graphic({ geometry: clickPoint, symbol: this.pointSymbol }); this.graphicsLayer.add(graphicPoint); var mGeometry = this.queryTaskGraphic.geometry; //获取绘制的要素 /* 判断查询方式 */ if (option.type === 'point') { if (self.onQueryPointComplete) self.onQueryPointComplete(mGeometry); self.queryTaskGraphic = undefined; } else if (option.type === 'polygon') { //绘制的是查询面 且点数大于等于3 if (mGeometry.type == 'polygon' && mGeometry.rings[0].length >= 3) { if (self.onQueryPolygonComplete) onQueryPolygonComplete(3, mGeometry); self.queryTaskGraphic = undefined; } } }, /** * 根据空间要素进行查询 * @param {Object} geometry 参考要素 */ _queryLayersTaskFromGeometry: function(geometry) { let self = this; require([ "esri/rest/support/IdentifyParameters", "esri/rest/identify", "esri/geometry/SpatialReference", "esri/geometry/Polygon", "esri/geometry/Polyline", "esri/geometry/Point", ], function(IdentifyParameters, identify, SpatialReference, Polygon, Polyline, Point) { /* 定义查询地址 */ let url = self.queryURL; /* 组织查询的Id数组 */ let queryIds = []; for (let i in self.queryLayers) { queryIds.push(parseInt(self.queryLayers[i].id)); } /* 定义查询参数 */ let parameters = new IdentifyParameters({ tolerance: 3, layerIds: queryIds, geometry: geometry, mapExtent: self.mapView.extent, returnGeometry: true, layerOption: 'all', }) /* 结果集合 */ let results = []; /* 开始查询之前传递个事件出去,显示等待框 */ if (self.onQueryLayersTaskBegin) self.onQueryLayersTaskBegin(); /* 打印测试 */ // console.log("查询图层 = " + JSON.stringify(self.queryLayers)); // console.log("查询图层Id = " + JSON.stringify(queryIds)); /* 开始查询 */ identify.identify(url, parameters).then(function(response) { // console.log("成功"); /* 对数据进行组合 */ for (let i in response.results) { let item = response.results[i]; /* 创建要素 */ let geometry = undefined; let geometryType = item.feature.geometry.type; if (geometryType === 'polygon') { geometry = new Polygon({ spatialReference: { wkid: item.feature.geometry .spatialReference .wikd, }, rings: item.feature.geometry.rings, }) } else if (geometryType === 'polyline') { geometry = new Polyline({ spatialReference: { wkid: item.feature.geometry .spatialReference .wikd, }, paths: item.feature.geometry.paths, }) } else if (geometryType === 'point') { geometry = new Polyline({ spatialReference: { wkid: item.feature.geometry .spatialReference .wikd, }, x: item.feature.geometry.x, y: item.feature.geometry.y, }) } /* 返回的要素不符合要求 则进入下一次循环 */ if (geometry == undefined) continue; let extent = geometry.extent; /* 过滤数组 */ let layerConfigs = self.queryLayers.filter(function( p) { return p.eName.toUpperCase() === item .layerName; }); let layerConfig = layerConfigs[0]; /* 创建结果要素 */ let resultFeature = { fId: item.feature.attributes['OBJECTID'], sValue: item.feature.attributes[layerConfig .fldName .toUpperCase()], xmin: extent.xmin, ymin: extent.ymin, xmax: extent.xmax, ymax: extent.ymax, xcenter: extent.center.x, ycenter: extent.center.y, // attribute: item.feature.attributes, } /* 结果集中是否已经存在 */ let isExists = false; for (let rIdx in results) { let result = results[rIdx]; if (result.eName == item.layerName) { result.features.push(resultFeature) isExists = true; break; } } /* 如果不存在 */ if (!isExists) { results.push({ eName: item.layerName, cName: layerConfig.cName, features: [resultFeature] }) } } /* 回调返回结果 */ if (self.onQueryLayersTaskComplete) self .onQueryLayersTaskComplete( results); }); } ); }, }) /**+++++++++++++++测量相关+++++++++++++++++++++++*/ JTMapKit.prototype.extend({ /** * @param {string} type 测量类型 point/polyline/polygon * @param {JSON} option 配置项 */ _measure: function(type, option) { var self = this; //清除已绘制内容 self.clearGraphic(); self.isDrawing = true; require([ "esri/views/draw/Draw", "esri/layers/GraphicsLayer", "esri/Graphic" ], function(Draw, GraphicsLayer, Graphic) { /* 判断绘制图层是否存在 如果不存在 则创建 并加入到地图中 */ if (!self.graphicsLayer) { self.graphicsLayer = new GraphicsLayer(); self.map.layers.add(self.graphicsLayer); } /* 判断绘制工具是否已经实例化 如果未实例化则创建 否则重置 */ if (!self.draw) { self.draw = new Draw({ view: self.mapView }); } else { self.draw.reset(); } /* 未绘制工具创建动作 因为reset会清除已添加的动作 */ action = self.draw.create(type, { mode: 'click' }); option.type = type; //添加点 action.on("vertex-add", function(evt) { self._measureActionHandler(evt, option, Graphic); }); //绘制结束 action.on("draw-complete", function(evt) { self.isDrawing = false; self._measureActionHandler(evt, option, Graphic); }); //删除点 action.on("vertex-remove", function(evt) { self._measureActionHandler(evt, option, Graphic); }); }); }, /** * 处理绘制事件 * @param {JSON} evt 事件 * @param {JSON} option 配置项 * @param {Object} Graphic 要素类原型 */ _measureActionHandler(evt, option, Graphic) { var geometry, clickPoint; if (evt.coordinates) { //绘制单个点时获取的是coordinates var coordinates = evt.coordinates; clickPoint = geometry = { type: "point", x: coordinates[0], y: coordinates[1], spatialReference: this.mapView.spatialReference }; } else if (evt.vertices) { var vertices = evt.vertices; var type = option.type; //创建点击点 以便实现效果 clickPoint = { type: "point", x: vertices[vertices.length - 1][0], y: vertices[vertices.length - 1][1], spatialReference: this.mapView.spatialReference }; geometry = { spatialReference: this.mapView.spatialReference }; if (type === 'polyline') { geometry.paths = vertices; geometry.type = "polyline"; } else { geometry.rings = vertices; geometry.type = "polygon"; } } if (!this.measureGraphic) { this.measureGraphic = new Graphic({ geometry: geometry, symbol: option.symbol }); this.graphicsLayer.add(this.measureGraphic); } else { this.measureGraphic.geometry = geometry; } //追加点击点 var graphicPoint = new Graphic({ geometry: clickPoint, symbol: this.pointSymbol }); this.graphicsLayer.add(graphicPoint); /* 判断是否需要计算并返回结果 */ var self = this; var mGeometry = this.measureGraphic.geometry; //获取绘制的要素 if (mGeometry.type == "polyline") { if (mGeometry.paths[0].length >= 2) { this._measureLengthOrAreaOrCoord(function(lastLength, allLength) { self._measureAddText(lastLength, clickPoint); // self._showMeasureResultPopup("长度测量结果", "当前测量总长:" + allLength, clickPoint); if (self.onMeasureEventComplete != undefined) { self.onMeasureEventComplete('length', "当前测量总长:" + allLength); } }); } else { this._measureAddText('起点', clickPoint); } } else if (mGeometry.type == "polygon") { if (mGeometry.rings[0].length >= 3) { this._measureLengthOrAreaOrCoord(function(result) { // self._showMeasureResultPopup("面积测量结果", result, clickPoint); if (self.onMeasureEventComplete != undefined) { self.onMeasureEventComplete('area', result); } }); } else if (mGeometry.rings[0].length == 1) { this._measureAddText('起点', clickPoint); } } else if (mGeometry.type == "point") { this._measureLengthOrAreaOrCoord(function(result) { // self._showMeasureResultPopup("当前位置坐标", result, clickPoint); if (self.onMeasureEventComplete != undefined) { self.onMeasureEventComplete('coord', result); } }); } }, /** * 添加文字 * @param {string} text * @param {EsriPoint} location 文字位置 */ _measureAddText: function(text, location) { var self = this; require(["esri/Graphic"], function(Graphic) { /* 创建文字符号 */ // var textSymbol = { // type: 'text', // color: "#FFFFFF", // haloColor: "#555555", // haloSize: "2px", // text: text, // xoffset: 0, // yoffset: -20, // font: { // size: 10, // family: "Playfair Display", // weight: "bold" // } // }; self.textSymbol.text = text; /* 创建文字要素 */ var txtGraphic = new Graphic({ geometry: location, symbol: self.textSymbol }); /* 将文字要素添加到绘制图层 */ self.graphicsLayer.add(txtGraphic); }); }, /** * 转换线的长度 * @param {float} lineLength 线的长度 */ _measureTrasformLineLength: function(lineLength) { var len = parseFloat(lineLength); var lenResult = ""; if (len < 1000) { lenResult = len.toFixed(2) + "米"; } else { lenResult = (len / 1000).toFixed(2) + "公里"; } return lenResult; }, /** * 根据绘制图层绘制的要素类型 计算坐标、长度或者面积 * @param {function} callback 计算完成回调 */ _measureLengthOrAreaOrCoord: function(callback) { var self = this; require([ "esri/geometry/support/geodesicUtils", "esri/geometry/projection", "esri/geometry/SpatialReference", "esri/geometry/geometryEngine", "esri/geometry/geometryEngineAsync" ], function(geodesicUtils, projection, SpatialReference, geometryEngine, geometryEngineAsync) { //设置要素的投影 self.measureGraphic.geometry.spatialReference = self.mapView .spatialReference; //定义坐标系 var outSpatialReference = new SpatialReference({ wkid: 4326 }); var mGeometry = self.measureGraphic.geometry; if (mGeometry.type == "polyline") { //计算最后一段长度 var pt1 = mGeometry.getPoint(0, mGeometry.paths[0].length - 1); var pt2 = mGeometry.getPoint(0, mGeometry.paths[0].length - 2); //创建要素 var lastGeometry = { spatialReference: self.mapView.spatialReference, type: "polyline", paths: [ [ [pt1.x, pt1.y], [pt2.x, pt2.y] ] ], }; lastGeometry.spatialReference = self.mapView.spatialReference; //开始异步计算长度 geometryEngineAsync.geodesicLength(lastGeometry, "meters").then( function( lastResult) { geometryEngineAsync.geodesicLength(mGeometry, "meters").then( function( result) { var lenLastResult = self ._measureTrasformLineLength( lastResult); var lenAllResult = self ._measureTrasformLineLength( result); if (callback != undefined) callback( lenLastResult, lenAllResult); }) }); } else if (mGeometry.type == "polygon") { var result = geometryEngine.geodesicArea(mGeometry, "square-meters"); var area = Math.abs(parseFloat(result)); //如果初次计算的面积小于0 说明坐标串是反序的 将其反过来 重新计算 if (area < 0) { // mGeometry.rings[0].reverse(); // alert(mGeometry.rings[0]); // result = geometryEngine.geodesicArea(mGeometry, "square-meters"); // area = parseFloat(result[0]); } var areaMu = area * 0.0015; var areaResult = ""; if (area < 1000000) { areaResult = area.toFixed(3) + "平方米 " + areaMu.toFixed(3) + "亩"; } else { areaResult = (area / 1000000).toFixed(3) + "平方公里 " + areaMu .toFixed(3) + "亩"; } if (callback != undefined) callback(areaResult); } else if (mGeometry.type == "point") { //对坐标进行转换 projection.load().then(function() { var geometry = projection.project(mGeometry, outSpatialReference); var coordResult = "经度:" + geometry.x.toFixed(6) + " 纬度:" + geometry.y .toFixed(6); if (callback != undefined) callback(coordResult); }); } } ); }, /** * 显示测量结果 * @param {string} title 标题 * @param {string} content 测量结果内容 * @param {ESRIPoint} location 测量结果内容 */ _showMeasureResultPopup: function(title, content, location) { /* 显示弹窗试试 */ var popup = this.mapView.popup; /* 显示位置 */ popup.location = location; /* 设置标������� */ popup.title = title; /* �����置显示内容 */ popup.viewModel.content = content; /* 控制窗口的停靠按钮是否显示 */ popup.dockOptions = { buttonEnabled: false, } /* 控制是否显示关闭按钮 */ popup.visibleElements = { closeButton: true, featureNavigation: false } /* 关闭自动缩放按钮 */ popup.viewModel.includeDefaultActions = false; /* 控制是否������������������������ */ popup.visible = true; }, //测量长度 measureLength: function(option) { var options = option || {}; if (!options.symbol) { options.symbol = this.lineSymbol; } this._measure('polyline', options); }, //测量面积 measureArea: function(option) { var options = option || {}; if (!options.symbol) { options.symbol = this.fillSymbol; } this._measure('polygon', options); }, //测量坐标 measureCoordinate: function(option) { var options = option || {}; if (!options.symbol) { options.symbol = this.pointSymbol; } this._measure('point', options); } }) /**+++++++++++++++图层操作相关+++++++++++++++++++++++*/ JTMapKit.prototype.extend({ /** * 根据���层名称设置其可见性 * @param {any} layerName 图层名称 * @param {any} isVisible 是否可见 */ _setLayerIsVisibleByName: function(layerName, isVisible) { this.map.layers.forEach(function(layer, idx) { if (layer.title && layer.title.toLocaleLowerCase() == layerName .toLocaleLowerCase()) { layer.visible = isVisible; return idx; } }); }, /** * 根据图层名称查找图层 * @param {string} layerName */ findLayer: function(layerName) { let findLayer = this.map.allLayers.find(function(layer) { return layer.title === layerName; }); if (findLayer) return findLayer; else return undefined; }, /** * 删除指定名称的图层 * @param {string} layerName 图层名称 */ removeLayer: function(layerName, callSuccess, callError) { let _self = this; let findLayer = this.map.allLayers.find(function(layer) { return layer.title === layerName; }) if (findLayer) { this.map.layers.remove(findLayer); if (callSuccess) callSuccess(); } else { if (callError) callError("名称为" + layerName + "的图层不存在,无法完成删除!" ); } }, /** * 设�����图层可见及不可见 * @param {any} visibleLayerNames * @param {any} noVisibleLayerNames */ setVisibleByNames: function(visibleLayerNames, noVisibleLayerNames) { var self = this; for (var i = 0; i < self.loadLayers.length; i++) { var layer = self.loadLayers[i]; if (visibleLayerNames.indexOf(layer.title) != -1) { layer.slayer.findSublayerById(layer.id).visible = true; } if (noVisibleLayerNames.indexOf(layer.title) != -1) { layer.slayer.findSublayerById(layer.id).visible = false; } } }, /** 设置单个图层可见或隐藏 * @param {string} layerName 图层名称 * @param {boolean} visible 显示或隐藏 */ setVisibleByName: function(layerName, visible) { this._setLayerIsVisibleByName(layerName, visible); }, /** * 设置图层标注是否可见 * @param {string} layerName 图层名称 * @param {boolean} visible 标注是否可见 */ setLabelVisibleByName: function(layerName, visible) { this.map.layers.forEach(function(layer, idx) { if (layer.title.toLocaleLowerCase() == layerName .toLocaleLowerCase()) { layer.sublayers.find(function(subLayer) { subLayer.labelsVisible = visible; }); } }); }, }); /**++++++++++++其他相关内内容++++++++++++++++++++++*/ JTMapKit.prototype.extend({ /** * 初始化 * @param {function} callback 成功回调 */ DeleteTempDraw: function(callback) { this.clearGraphic(); this.currentActionType = this.actionType.unknown; //初始化状态 if (callback) callback(); }, /** * 地图输出 * @param {any} title 标题 * @param {any} layout 模式 A3���式 A3竖式 A4横式 A4竖式 * @param {any} restype 返回���式 */ PrintMap: function(title, layout, restype) { var self = this; var scale = self.mapView.scale > 1000000 ? 3000 : self.mapView.scale; var sLayout = layout; if (layout == "A3横向") { sLayout = "a3-landscape"; } else if (layout == "A3竖向") { sLayout = "a3-portrait"; } else if (layout == "A4横向") { sLayout = "a4-landscape"; } else if (layout == "A4竖向") { sLayout = "a4-portrait"; } require([ "esri/tasks/PrintTask", "esri/tasks/support/PrintParameters", "esri/tasks/support/PrintTemplate" ], function(PrintTask, PrintParameters, PrintTemplate) { //此方法是为了关闭标注层 否则打印的地图将出现黑色 self._setLayerIsVisibleByName("天地图���注", false); var printTask = new PrintTask({ url: "http://218.59.194.74:6080/arcgis/rest/services/Utilities/PrintingTools/GPServer/Export%20Web%20Map%20Task", }); //打印模板 var template = new PrintTemplate({ format: restype, exportOptions: { dpi: 100, width: self.mapView.width, height: self.mapView.height }, layout: sLayout, layoutOptions: { titleText: title, authorText: "" }, outScale: scale, }); //打印参数 var params = new PrintParameters({ view: self.mapView, template: template }); if (self.onPrintEventProgress) { self.onPrintEventProgress(false); } //执行输出地图 printTask.execute(params).then(function(result) { self._setLayerIsVisibleByName("天地图标注", true); if (self.onPrintEventProgress) self .onPrintEventProgress(true); if (self.onPrintEventComplete) { self.onPrintEventComplete(result.url); } }, function(error) { self._setLayerIsVisibleByName("天地图标注", true); if (self.onPrintEventProgress) self .onPrintEventProgress(true); if (self.onEventError) { self.onEventError(error); } }); } ); }, /** * 向地图中添加点 * @param {any} x * @param {any} y */ AddPointToMap: function(x, y) { var self = this; require([ "esri/symbols/PictureMarkerSymbol", "esri/geometry/Point", "esri/geometry/SpatialReference", "esri/layers/GraphicsLayer", "esri/Graphic", "esri/geometry/geometryEngine" ], function(PictureMarkerSymbol, Point, SpatialReference, GraphicsLayer, Graphic, geometryEngine) { if (!self.graphicsLayer) { self.graphicsLayer = new GraphicsLayer(); self.map.layers.add(self.graphicsLayer); } //定义坐标系统 var spa = new SpatialReference({ wkid: 4326, }); //定义符号 var ptSymbol = new PictureMarkerSymbol({ url: self.serverUrl + "location02.png", width: "20px", height: "20px", xoffset: 0, yoffset: 7, }); //定义点 var pt = new Point({ x: x, y: y, spatialReference: spa, }); //定义要素 var graphicPt = new Graphic({ geometry: pt, symbol: ptSymbol, }); //添加要素 self.graphicsLayer.add(graphicPt); //超�����范围则重新定���地图中��� if (!geometryEngine.intersects(pt, self.mapView.extent)) { self.mapView.center = [x, y]; } } ); }, /** * 将点数组追加到地图中 * @param {any} points */ AddPointsToMap: function(points) { var self = this; require([ "esri/symbols/SimpleLineSymbol", "esri/symbols/SimpleMarkerSymbol", "esri/Color", "esri/geometry/Polyline", "esri/geometry/Point", "esri/geometry/SpatialReference", "esri/layers/GraphicsLayer", "esri/Graphic" ], function(SimpleLineSymbol, SimpleMarkerSymbol, Color, Polyline, Point, SpatialReference, GraphicsLayer, Graphic) { if (!self.graphicsLayer) { self.graphicsLayer = new GraphicsLayer(); self.map.layers.add(self.graphicsLayer); } //定义坐标系统 var spa = new SpatialReference({ wkid: 4326, }); //定义颜色 var r = Math.floor(Math.random() * 200);; var g = Math.floor(Math.random() * 200); var b = Math.floor(Math.random() * 200); var rgb = [r, g, b]; var ptColor = new Color([34, 139, 34, 1]); var lineColorBack = new Color([255, 255, 255]); var lineColor = new Color(rgb); //定义点样式 var ptSymbol = new SimpleMarkerSymbol({ style: "circle", color: ptColor, size: "8px", // pixels }); //定义线样式 var lineSymbolBack = new SimpleLineSymbol({ color: lineColorBack, width: "5px", style: "solid" }); //定义线样式 var lineSymbol = new SimpleLineSymbol({ color: lineColor, width: "2px", style: "solid" }); //加载数据 var paths = []; var pointStart, pointEnd; for (var i = 0; i < points.length; i++) { if (i == 0) { pointStart = new Point({ x: points[i].x, y: points[i].y, spatialReference: spa, }); } if (i == points.length - 1) { pointEnd = new Point({ x: points[i].x, y: points[i].y, spatialReference: spa, }); } paths.push([points[i].x, points[i].y]); } //创建线 var lineBack = new Polyline({ paths: paths, spatialReference: spa, }); var line = new Polyline({ paths: paths, spatialReference: spa, }); //创建要素 var graphicBack = new Graphic({ geometry: lineBack, symbol: lineSymbolBack, }); var graphic = new Graphic({ geometry: line, symbol: lineSymbol, }); var graphicStr = new Graphic({ geometry: pointStart, symbol: ptSymbol, }); var graphicEnd = new Graphic({ geometry: pointEnd, symbol: ptSymbol, }); //添加要素 self.graphicsLayer.add(graphicBack); self.graphicsLayer.add(graphic); self.graphicsLayer.add(graphicStr); self.graphicsLayer.add(graphicEnd); //定位范围 self.mapView.extent = line.extent; } ); }, /** * 将polygon添加到地图 * @param {JSON} options * points{Array}:[{longitude,latitude},{longitude,latitude},...] * lineColor{Array}:[r,g,b,a] * fillColor{Array}:[r,g,b,a] * success{Function}: 回调 */ AddPolygonToMap: function(options) { var self = this; require([ "esri/symbols/SimpleLineSymbol", "esri/symbols/SimpleFillSymbol", "esri/Color", "esri/geometry/Polygon", "esri/geometry/SpatialReference", "esri/layers/GraphicsLayer", "esri/Graphic" ], function(SimpleLineSymbol, SimpleFillSymbol, Color, Polygon, SpatialReference, GraphicsLayer, Graphic) { if (!self.graphicsLayer) { self.graphicsLayer = new GraphicsLayer(); self.map.layers.add(self.graphicsLayer); } //定义坐标系统 var spa = new SpatialReference({ wkid: 4326, }); //定义颜色 var fillColor = options.fillColor == undefined ? new Color([0, 0, 255, 0.3 ]) : options .fillColor; var lineColor = options.lineColor == undefined ? new Color([255, 0, 0, 0.5 ]) : options .lineColor; //定义线样式 var lineSymbol = new SimpleLineSymbol({ color: lineColor, width: "2px", style: "solid" }); //定义面样式 var fullSymbol = new SimpleFillSymbol({ color: fillColor, style: "solid", outline: lineSymbol, }); //构建数据 var rings = [ [] ]; for (var i in options.points) { var point = options.points[i] rings[0].push([point.longitude, point.latitude]); } //创建区域 var polygon = new Polygon({ rings: rings, spatialReference: spa, }); //创建要素 var graphicPolygon = new Graphic({ geometry: polygon, symbol: fullSymbol, }); //添加要素 self.graphicsLayer.add(graphicPolygon); if (options.success != undefined) options.success(graphicPolygon); //定位范围 self.mapView.extent = graphicPolygon.extent; } ); }, /** * 删除绘制的临时要素 * @param {Object} graphic 绘制的要素 */ removeGrahpic: function(graphic) { if (graphic != undefined) { if (this.graphicsLayer) { this.graphicsLayer.remove(graphic); } } }, /** * 删除全部绘制的临时要素 */ removeAllGraphic: function() { if (this.graphicsLayer) { this.graphicsLayer.removeAll(); } }, /** * 绘制Polygon,MultPolygon到临时图层 * @param {JSON} options 配置项 * options.lineColor{array}:[r,g,b,a] * options.fillColor{Array}:[r,g,b,a] * options.type{string}:绘制的区域类型 Polygon/MultiPolygon * options.coordinates{array}:绘制区域的坐标串 */ appendPolygonToMap: function(options) { var _self = this; require([ "esri/symbols/SimpleLineSymbol", "esri/symbols/SimpleFillSymbol", "esri/Color", "esri/geometry/Polygon", "esri/geometry/SpatialReference", "esri/layers/GraphicsLayer", "esri/Graphic" ], function(SimpleLineSymbol, SimpleFillSymbol, Color, Polygon, SpatialReference, GraphicsLayer, Graphic) { /* 判断临时绘制图层是否存在 不存在则创建 */ if (!_self.graphicsLayer) { _self.graphicsLayer = new GraphicsLayer(); _self.map.layers.add(_self.graphicsLayer); } else { _self.graphicsLayer.removeAll(); } /* 定义绘制要素的坐标系统 */ let spa = new SpatialReference({ wkid: 4326, }); /* 定义颜色 */ let fillColor = options.fillColor == undefined ? new Color([0, 0, 255, 0.2 ]) : options .fillColor; let lineColor = options.lineColor == undefined ? new Color([255, 255, 255, 0.8 ]) : options .lineColor; /* 定义符号样式 */ var lineSymbol = new SimpleLineSymbol({ color: lineColor, width: "2px", style: "short-dash-dot-dot" }); let fullSymbol = new SimpleFillSymbol({ color: fillColor, style: "solid", outline: lineSymbol, }); /* 绘制的要素 */ let graphics = []; /* 根据类型进行绘制 */ if (options.type === 'Polygon') { /* 创建区域 */ let polygon = new Polygon({ rings: options.coordinates, spatialReference: spa, }); /* 绘制区域 */ let graphicPolygon = new Graphic({ geometry: polygon, symbol: fullSymbol, }); /* 添加要素 */ graphics.push(graphicPolygon); } else if (options.type === 'MultiPolygon') { for (rings of options.coordinates) { /* 创建区域 */ let polygon = new Polygon({ rings: rings, spatialReference: spa, }); /* 绘制区域 */ let graphicPolygon = new Graphic({ geometry: polygon, symbol: fullSymbol, }); /* 添加要素 */ graphics.push(graphicPolygon); } } /* 绘制 */ _self.graphicsLayer.addMany(graphics); /* 缩放至位置 */ // _self.mapView.extent = graphics[0].geometry.extent; // _self.mapView.zoom = _self.mapView.zoom - 1; _self.mapView.goTo(graphics[0].geometry.extent, { duration: 500 }).then(function() { _self.mapView.zoom = _self.mapView.zoom - 1; console.log("设置地图缩放等级 = " + _self.mapView.zoom); }); } ); }, }); /** * 扩展工具 */ JTMapKit.prototype.extend({ /** * 启用草图编辑工具 * @param {JSON} options 配置项 * options.onadded{function}:添加点回调 * options.onredo{function}:恢复回调 * options.onundo{function}:撤销回调 * @param {function} callSuccess 成功回调 */ _sketchToolsInit: function(options, callSuccess) { /* 自身替换 */ let _self = this; require([ "esri/layers/GraphicsLayer", "esri/widgets/Sketch/SketchViewModel", "esri/geometry/projection", "esri/geometry/SpatialReference" ], function(GraphicsLayer, SketchViewModel, projection, SpatialReference) { /* 判断是否存在草图图层 不存在则创建并加入地图中 */ if (!_self.layerSketch) { _self.layerSketch = new GraphicsLayer(); _self.map.add(_self.layerSketch); } /* 草图辅助图层 */ if (!_self.graphicsLayer) { _self.graphicsLayer = new GraphicsLayer(); _self.map.layers.add(_self.graphicsLayer); } else { _self.graphicsLayer.removeAll(); } /* 判断草图工具是否存在 不存在则创建 */ if (!_self.sketchViewModel) { _self.sketchViewModel = new SketchViewModel({ layer: _self.layerSketch, view: _self.mapView, pointSymbol: _self.sketchPointSymbol, polylineSymbol: _self.sketchLineSymbol, polygonSymbol: _self.sketchPolygonSymbol, }); /* 绑定创建事件 */ _self.sketchViewModel.on("create", function(event) { if (event.state == "start") { _self.layerSketch.removeAll(); //删除全部 } if (event.toolEventInfo && event.toolEventInfo .type === "vertex-add") { if (options && options.onadded) options.onadded( event .graphic .geometry); } if (event.state === 'complete') { if (options && options.oncomplete) options .oncomplete(event .graphic .geometry); } }); /* 绑定redo事件 */ _self.sketchViewModel.on('redo', function(event) { if (event.graphics && options && options.onredo) options.onredo( event .graphics[0] .geometry); }); /* 绑定undo事件 */ _self.sketchViewModel.on('undo', function(event) { if (event.graphics && options && options.onundo) options.onundo( event .graphics[0] .geometry); }); /* 回调 */ if (callSuccess) callSuccess(); } }); }, /** * 启用草图工具 * @param {string} type 工具类型 * @param {JSON} options 配置项 */ _activeSketchTools: function(type, options) { let _self = this; /* 如果草图编辑工具已经初始化 则释放资源 重新初始化 */ if (this.sketchViewModel) { this.sketchViewModel.layer.graphics.removeAll(); this.sketchViewModel.destroy(); this.sketchViewModel = null; } /* 初始化草图工具 */ this._sketchToolsInit(options, function() { /* 启用草图工具 */ if (type === 'point') { _self.sketchViewModel.create('point'); } else if (type === 'line') { _self.sketchViewModel.create('polyline'); } else if (type === 'rectangle') { _self.sketchViewModel.create('rectangle'); } else { _self.sketchViewModel.create('polygon'); } }); }, /** * 草图编辑工具完成确认 */ _sketchComplete: function() { if (this.sketchViewModel) { this.sketchViewModel.complete(); } }, /** * 启用点草图工具 * @param {JSON} options 配置项 */ activeSketchPointTools: function(options) { this._activeSketchTools('point', options); }, /** * 启用线草图工具 * @param {JSON} options 配置项 */ activeSketchLineTools: function(options) { this._activeSketchTools('line', options); }, /** * 启用矩形草图工具 * @param {JSON} options 配置项 */ activeSketchRectangleTools: function(options) { this._activeSketchTools('rectangle', options); }, /** * 启用区域草图工具 * @param {JSON} options 配置项 */ activeSketchPolygonTools: function(options) { this._activeSketchTools('polygon', options); }, /** * 草图编辑提交 */ sketchComplete: function() { this._sketchComplete(); }, }) /** * 草图功能扩展 */ JTMapKit.prototype.extend({ /** * 多图层查询 点方式 * @param {JSON} options 配置项 * options.queryLayers{JSON}:查询图层参考 * options.url{string}:查询地址 * @param {function} callSuccess 成功回调 * callSuccess({}) * @param {function} callError 错误回调 * callError(string) */ manyLayerQueryByPoint: function(options, callSuccess, callError) { let _self = this; _self.activeSketchPointTools({ oncomplete: function(geometry) { _self.manyLayerQuery({ geometry: geometry, queryLayers: options.queryLayers, url: options.url }, callSuccess, callError); } }) }, /** * 多图层查询 绘制区域方式 * @param {JSON} options 配置项 * options.queryLayers{JSON}:查询图层参考 * options.url{string}:查询地址 * @param {function} callOperation 操作回调 * callOperation({}) * @param {function} callSuccess 成功回调 * callSuccess({}) * @param {function} callError 错误回调 * callError(string) */ manyLayerQueryByPolygon: function(options, callOperation, callSuccess, callError) { let _self = this; _self.activeSketchPolygonTools({ onadded: function(geometry) { if (callOperation) callOperation({ geometry: geometry, }) }, oncomplete: function(geometry) { _self.manyLayerQuery({ geometry: geometry, queryLayers: options.queryLayers, url: options.url }, callSuccess, callError); } }) }, /** * 多图层查询 绘制区域方式 查询确认 */ manyLayerQueryByPolygonComplete: function() { this._sketchComplete(); }, /** * 多图层查询 * @param {JSON} options 配置项 * options.geometry{JSON}:查询参考图形要素 * options.url{string}:查询地址 * options.queryLayers{array{JSON}}:查询图层集合 * @param {function} callSuccess 成功回调 * callSuccess({}) * @param {function} callError 错误回调 * callError(string) */ manyLayerQuery: function(options, callSuccess, callError) { let _self = this; require([ "esri/rest/support/IdentifyParameters", "esri/rest/identify" ], function(IdentifyParameters, identify) { /* 过滤查询的图层 */ let queryIds = []; for (let layer of options.queryLayers) { queryIds.push(parseInt(layer.id)); } /* 设置查询参数 */ let params = new IdentifyParameters({ geometry: options.geometry, mapExtent: _self.mapView.extent, returnGeometry: true, tolerance: 3, layerIds: queryIds, layerOption: 'all', }); identify.identify(options.url, params).then(function(response) { /* 查询结果 */ let results = []; /* 循环查询数据集 */ for (let item of response.results) { /* 巡查查询数据对应的配置图层 */ let layers = options.queryLayers.filter(function( p) { return p.eName.toUpperCase() === item .layerName; }); let layer = layers[0]; /* 创建结果要素 */ let resultFeature = { fId: item.feature.attributes['OBJECTID'], tabName: layer.eName, sValue: item.feature.attributes[layer .fldName .toUpperCase()], } /* 结果集中是否已经存在 */ let isExists = false; for (let result of results) { if (result.eName == item.layerName) { result.features.push(resultFeature) isExists = true; break; } } /* 如果不存在 */ if (!isExists) { results.push({ eName: item.layerName, cName: layer.cName, isCase: layer.isCase, features: [resultFeature] }) } } /* 返回结果 */ if (results.length === 0 && callError) callError( "未查询到任何数据!"); if (results.length > 0 && callSuccess) callSuccess( results); }); }); }, /** * 通用占压分析 * @param {function} callSuccess 成功回调 * @param {function} callError 失败回调 */ commonOccupyAnalysis: function(callSuccess, callError) { let _self = this; require([ "esri/geometry/projection", "esri/geometry/SpatialReference" ], function(projection, SpatialReference) { /* 定义输出投影 */ let outSReference = new SpatialReference({ wkid: 4326, }); _self.activeSketchPolygonTools({ onadded: function(geometry) { /* 进行坐标转换 */ projection.load().then(function() { let outGeometry = projection .project(geometry, outSReference); let outCoordinate = undefined; for (let ring of outGeometry.rings[ 0]) { if (outCoordinate) { outCoordinate += "," + ring[ 0] + "," + ring[1]; } else { outCoordinate = ring[0] + "," + ring[1]; } } /* 回调输出 */ if (callSuccess) callSuccess( outCoordinate); }) } }) }); }, /** * 占压分析 * @param {JSON} options 配置项 * @param {String} options.url 查询地址 * @param {Array} options.queryLayers 查询配置表 * @param {function} callSuccess 成功回调callSuccess({tabName:features:{objId:showName}}) * @param {function} callError 错误回调callError(string) */ occupyAnalysis: function(options, callSuccess, callError) { let _self = this; require([ "esri/rest/support/IdentifyParameters", "esri/rest/identify" ], function(IdentifyParameters, identify) { /* 启用草图工具 */ _self.activeSketchPointTools({ onadded: function(geometry) { let params = new IdentifyParameters({ geometry: geometry, mapExtent: _self.mapView.extent, returnGeometry: true, tolerance: 3, layerOption: 'all', }); identify.identify(options.url, params).then( function( response) { /* 查询结果 */ let qResults = []; /* 循环查询结果 */ for (let item of response.results) { let layerName = item.layerName .toUpperCase(); /* 巡查查询数据对应的配置图层 */ let layers = options.queryLayers .filter( function( p) { return p.eName .toUpperCase() === layerName; }); let configLayer = layers != undefined && layers .length > 0 ? layers[0] : undefined; if (configLayer === undefined) continue; let tabCName = configLayer .cName; let fldName = configLayer .fldName; /* 创建返回要素 */ let objId = item.feature .attributes[ 'OBJECTID']; let showName = item.feature .attributes[ fldName .toUpperCase()]; let feature = { objId: objId, tabName: layerName, showName: showName, } /* 寻找 */ let tempResults = qResults .filter(function( p) { return p .tabEName === layerName; }) if (tempResults === undefined || tempResults .length === 0) { qResults.push({ tabEName: layerName, tabCName: tabCName, features: [ feature ], }) } else { tempResults[0].features .push(feature); } } /* 返回结果 */ if (qResults.length > 0 && callSuccess) { callSuccess(qResults); } else if (qResults.length === 0 && callError) { callError('未查询到任何数据!'); } }); } }) }); }, /** * 案件查询 点方式 * @param {JSON} options 配置项 * options.url{string}:查询地址 * options.filter{string}:案件查询过滤条件 * @param {function} callSuccess 成功回调 * callSuccess{array{string}} * @param {function} callError 错误回调 * callError{string} */ queryCaseByPoint: function(options, callSuccess, callError) { let _self = this; _self.activeSketchPointTools({ onadded: function(geometry) { _self._queryCaseFeature({ geometry: geometry, url: options.url, id: options.id }, callSuccess, callError); } }) }, /** * 案件查询 绘制区域方式 * @param {JSON} options 配置项 * options.url{string}:查询地址 * options.filter{string}:案件查询过滤条件 * @param {function} callOperation 操作回调 * callOperation({}) * @param {function} callSuccess 成功回调 * callSuccess{array{string}} * @param {function} callError 错误回调 * callError{string} */ queryCaseByPolygon: function(options, callOperation, callSuccess, callError) { let _self = this; _self.activeSketchPolygonTools({ onadded: function(geometry) { if (callOperation) callOperation({ geometry: geometry, }); }, oncomplete: function(geometry) { _self._queryCaseFeature({ geometry: geometry, url: options.url, id: options.id }, callSuccess, callError); } }) }, /** * 区域案件查询完成操作 */ queryCaseByPolygonComplete: function() { this._sketchComplete(); }, /** * 案件要素查询 * @param {JSON} options 配置项 * options.geometry{JSON}:查询参考要素 * options.url{string}:查询地址 * options.filter{string}:查询数据的过滤条件 * @param {function} callSuccess 成功回调 * callSuccess{array{string}} * @param {function} callError 错误回调 * callError{string} */ _queryCaseFeature: function(options, callSuccess, callError) { let _self = this; var self = this; require([ "esri/tasks/support/Query", "esri/tasks/QueryTask", ], function(Query, QueryTask) { /* 定义查询任务 */ let qTask = new QueryTask({ url: options.url }); /* 定义查询参数 */ let params = new Query({ returnGeometry: true, outFields: ["*"], distance: 3, geometry: options.geometry, spatialRelationship: "intersects", where: options.filter, }); /* 开始查询 */ qTask.execute(params).then(function(response) { let result = []; for (let feature of response.features) { result.push(feature.attributes['AJH']); } if (result.length === 0 && callError) callError( '未查询到任何案件!'); if (result.length > 0 && callSuccess) callSuccess( result); }); }); }, /** * 长度测量 * @param {function} callSuccess 成功回调 * callSuccess(float) */ eMeasureLength: function(callSuccess) { _self = this; /* 存储临时长度 */ _self.tempLen = 0; /* 绘制的文字要素集合 */ _self.drawLabelGraphics = []; _self.activeSketchLineTools({ onadded: function(geometry) { /* 传递的geometry为polyline类型 数据存储在paths中 */ let path = geometry.paths[0]; let pt = path[path.length - 1]; _self._measureLengthByGeometry(geometry, function(len) { let lenTemp = len - _self.tempLen; _self.tempLen = len; let showLen = _self._measureLengthTrasform( lenTemp); let label = len === 0 ? '起点' : showLen; _self._measureLengthAddLabel({ x: pt[0], y: pt[1], label: label }, function(graphic) { _self.drawLabelGraphics.push( graphic); }); /* 长度回调 */ if (len > 0 && callSuccess) callSuccess(_self ._measureLengthTrasform(len)); }) }, onredo: function(geometry) { /* 传递的geometry为polyline类型 数据存储在paths中 */ let path = geometry.paths[0]; let pt = path[path.length - 1]; _self._measureLengthByGeometry(geometry, function(len) { let lenTemp = len - _self.tempLen; _self.tempLen = len; let showLen = _self._measureLengthTrasform( lenTemp); let label = len === 0 ? '起点' : showLen; _self._measureLengthAddLabel({ x: pt[0], y: pt[1], label: label }, function(graphic) { _self.drawLabelGraphics.push( graphic); }); /* 长度回调 */ if (len > 0 && callSuccess) callSuccess(_self ._measureLengthTrasform(len)); }) }, onundo: function(geometry) { _self._measureLengthByGeometry(geometry, function(len) { /* 干掉最后一个 */ let graphic = _self.drawLabelGraphics.pop(); _self.graphicsLayer.graphics.remove(graphic); /* 赋值临时长度 */ _self.tempLen = len; /* 长度回调 */ if (callSuccess) callSuccess(_self ._measureLengthTrasform( len)); }); } }) }, /** * 面积测量 * @param {function} callSuccess 成功回调 * callSuccess(float) */ eMeasureArea: function(callSuccess) { let _self = this; _self.activeSketchPolygonTools({ onadded: function(geometry) { _self._measureAreaByGeometry(geometry, function(area) { if (callSuccess) callSuccess(_self ._measureAreaTrasform( area)); }); }, onredo: function(geometry) { _self._measureAreaByGeometry(geometry, function(area) { if (callSuccess) callSuccess(_self ._measureAreaTrasform( area)); }); }, onundo: function(geometry) { _self._measureAreaByGeometry(geometry, function(area) { if (callSuccess) callSuccess(_self ._measureAreaTrasform( area)); }); } }) }, /** * 查询坐标 * @param {function} callSuccess 成功回调 */ eMeasureCoordinate: function(callSuccess) { let _self = this; _self.activeSketchPointTools({ onadded: function(geometry) { require(["esri/geometry/SpatialReference", "esri/geometry/projection" ], function(SpatialReference, projection) { let outProject = new SpatialReference({ wkid: 4326, }); projection.load().then(function() { let outGeometry = projection .project(geometry, outProject); if (callSuccess) callSuccess({ x: outGeometry.x, y: outGeometry.y, }) }); }); } }); }, /** * 转换长度为字符串 * @param {float} len 长度 * @return {string} 带单位的长度表示 */ _measureLengthTrasform: function(len) { let strLen = len < 1000 ? len.toFixed(2) + '米' : (len / 1000).toFixed(2) + '公里'; return strLen; }, /** * 转换面积为字符串 * @param {float} area 面积 * @return {string} 带单位的面积表示 */ _measureAreaTrasform: function(area) { let strMuArea = (area * 0.0015).toFixed(2) + "亩"; let strGqArea = (area * 0.0001).toFixed(2) + "公顷"; let strArea = area < 1000000 ? area.toFixed(2) + "平方米 " + strMuArea : (area / 1000000) .toFixed(2) + "平方公里 " + strGqArea; return strArea; }, /** * 测量长度时添加标签 * @param {JSON} options 配置项 * options.x{float}:标注点位置x坐标 * options.y{float}:标注点位置y坐标 * options.label{string}:标注点文字 * @param {function} callSuccess 成功回调 * callSuccess(graphic) */ _measureLengthAddLabel: function(options, callSuccess) { let _self = this; require([ "esri/Graphic", "esri/geometry/Point" ], function(Graphic, Point) { _self.textSymbol.text = options.label; /* 创建文字要素 */ let txtGraphic = new Graphic({ geometry: new Point({ x: options.x, y: options.y, spatialReference: _self.mapView .spatialReference, }), symbol: _self.textSymbol }); /* 将文字要素添加到绘制图层 */ _self.graphicsLayer.add(txtGraphic); /* 回调 */ if (callSuccess) callSuccess(txtGraphic); }); }, /** * 计算长度 * @param {JSON} geometry 待计算要素 * @param {function} callSuccess 计算成功回调 * callSuccess({float}) */ _measureLengthByGeometry: function(geometry, callSuccess) { require([ "esri/geometry/geometryEngine" ], function(geometryEngine) { let len = geometryEngine.geodesicLength(geometry, "meters"); if (callSuccess) callSuccess(len); }); }, /** * 计算面积 * @param {JSON} geometry 待计算要素 * @param {function} callSuccess 计算成功回调 * callSuccess({float}) */ _measureAreaByGeometry: function(geometry, callSuccess) { require([ "esri/geometry/geometryEngine" ], function(geometryEngine) { let len = geometryEngine.geodesicArea(geometry, "square-meters"); if (callSuccess) callSuccess(len); }); } }) /* GPS定位及方向变化相关 */ JTMapKit.prototype.extend({ /** * 添加GPS位置 * @param {Object} options 配置项 * @param {String} options.longitude 定位经度 * @param {String} options.latitude 定位纬度 * @param {String} options.angle 角度 * @param {Function} callSuccess 成功回调callSuccess() */ _appendGPSSymbol: function(options, callSuccess) { let _self = this; require(["esri/Graphic", "esri/geometry/Point", "esri/geometry/SpatialReference", "esri/layers/GraphicsLayer" ], function(Graphic, Point, SpatialReference, GraphicsLayer) { /* 定义坐标系 */ let spatialReference = new SpatialReference({ wkid: 4326, }) /* 定义点 */ let gpsPoint = new Point({ x: parseFloat(options.longitude), y: parseFloat(options.latitude), spatialReferenct: spatialReference, }) /* 创建要素 */ if (_self.gpsGraphic === undefined) { _self.gpsGraphic = new Graphic({ geometry: gpsPoint, symbol: _self.gpsSysmbol, }) if (!_self.gpsLayer) { _self.gpsLayer = new GraphicsLayer(); _self.map.layers.add(_self.gpsLayer); } else { _self.gpsLayer.removeAll(); } _self.gpsLayer.graphics.add(_self.gpsGraphic); } else { _self.gpsGraphic.geometry = gpsPoint; } /* 定位要素 */ // _self.zoomTo(options.longitude, options.latitude); /* 成功回调 */ // console.log(options.longitude, options.latitude); if (callSuccess) callSuccess(); }); }, /** * 添加GPS位置 * @param {Object} options 配置项 * @param {String} options.longitude 定位经度 * @param {String} options.latitude 定位纬度 * @param {String} options.angle 角度 * @param {Function} callSuccess 成功回调callSuccess() */ gpsAppendToMap: function(options, callSuccess) { this._appendGPSSymbol(options, callSuccess); }, /** * 移除GPS符号 */ gpsRemoveFromMap: function() { /* 移除展示元素 */ if (this.gpsLayer != undefined) { this.gpsLayer.removeAll(); } /* 重置展示元素 */ this.gpsGraphic = undefined; }, /** * 设置GPS符号的角度 * @param {float} angle 角度 */ gpsSetAngle: function(angle) { if (this.gpsGraphic != undefined) { this.gpsSysmbol.angle = parseFloat(-1 * angle); this.gpsGraphic.symbol = this.gpsSysmbol; } } })