/** * 初始化函数 * @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: "12px", outline: { color: [255, 255, 0], width: 1 } } //起始点点符号 this.pointStrSymbol = { type: "simple-marker", style: "circle", color: "red", size: "12px", outline: { color: [255, 255, 0], width: 1 } } //终止点点符号 this.pointEndSymbol = { type: "simple-marker", style: "circle", color: "green", size: "12px", 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: [0, 0, 255], width: 1, cap: "round", join: "round" } //默认面符号 this.fillSymbol = { type: "simple-fill", color: [4, 90, 141, 0.3], style: "solid", outline: { color: [0, 0, 255], width: 1 } } //默认文字符号 this.textSymbol = { type: 'text', color: "#FFFFFF", haloColor: "#555555", haloSize: "2px", text: '', xoffset: 0, yoffset: -20, font: { size: 10, family: "Playfair Display", weight: "bold" } }; this.isDrawing = false; //正在绘制中,用于控制多点绘制 } /** * 原型中添加的方法 * @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.onDrawEventComplete = option.onDrawCompleteEvent; //绘制完成激活事件 this.onMeasureEventComplete = option.onMeasureCompleteEvent; //测量结束事件 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.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服务器 this.baseMapVectorURL = "http://{subDomain}.tianditu.gov.cn/DataServer?T=vec_w&x={col}&y={row}&l={level}&tk=944815e0a333f538646868d896ef7378"; this.baseMapVectorLabelURL = "http://{subDomain}.tianditu.gov.cn/DataServer?T=cva_w&x={col}&y={row}&l={level}&tk=944815e0a333f538646868d896ef7378"; this.baseMapRasterURL = "http://{subDomain}.tianditu.gov.cn/DataServer?T=img_w&x={col}&y={row}&l={level}&tk=944815e0a333f538646868d896ef7378"; this.baseMapRasterLabelURL = "http://{subDomain}.tianditu.gov.cn/DataServer?T=cia_w&x={col}&y={row}&l={level}&tk=944815e0a333f538646868d896ef7378"; //绘图相关 this.draw = undefined; if (this.mapType.toLocaleLowerCase() === '3d') { } else { this._init2dMap(); } }, /** 初始化二维地图 */ _init2dMap: function() { var self = this; require(["esri/Map", "esri/views/MapView", "esri/core/urlUtils"], function(Map, MapView, urlUtils) { //此项操作是为了设置代理 否则将无法使用TileLayer访问切片服务,导致跨域问题产生 //urlUtils.addProxyRule({ // urlPrefix: "http://218.59.194.82:6080/", // proxyUrl: "http://218.59.194.74:8088/DotNet/proxy.ashx" //}); self.map = new Map({ basemap: self.mapOption.basemap }); self.mapView = new MapView({ container: self.selector, map: self.map, }); //清空所有自带组件 self.mapView.ui.components = []; if (self.onViewReady) { self.onViewReady(self.mapView); } if (!self.loadLayers) { self.loadLayers = []; } self.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); } }); //地图视图实例化完成 if (self.onMapReady) { self.onMapReady(self.map, self.mapView); } }, function(error) { console.log("地图加载失败", error); }); }); }, /** * 设置范围 * @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; }); }, }); /**++++++++++++++添加小组件++++++++++++++++++++*/ 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-left", }); } } 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 {any} option 选项 * @param {any} index 添加到地图中在图层中的顺序 * @param {any} name 图层名称 * @param {any} callback 添加完成时回调 */ addDynamicLayer: function(option, index, name, callback) { if (!option) { return } var self = this; require(["esri/layers/MapImageLayer"], function(MapImageLayer) { // printToConsole(JSON.stringify(option)); var layer = new MapImageLayer(option); layer.title = name; //添加图层到视图中执行该代码 layer.on("layerview-create", function() { //循环所有子图层 layer.allSublayers.find(function(sublayer) { self._addLayerToLayers(sublayer.id, sublayer.title, sublayer .visible, "sublayer", layer); }); if (callback) { callback(layer.fullExtent); } }); layer.on("layerview-create-error", function(event) { alert(event.error.message); }); self.map.add(layer, index); }); }, /** * 添加发布的要素服务 单独一层 * @param {any} option 地图选项 * @param {any} index 地图图层索引 */ addFeatureLayer: function(option, index, name, callback) { if (!option) { return } option.outFields ? option.outFields : ["*"]; var self = this; require(["esri/layers/FeatureLayer"], function(FeatureLayer) { var layer = new FeatureLayer(option); layer.title = name; //添加图层到视图中执行该代码 layer.on("layerview-create", function(event) { //将该图层添加到图层中 _addLayerToLayers(layer.id, layer.title, layer.visible, "featurelayer", undefined); if (callback) { callback(); } }); layer.on("layerview-create-error", function(event) { alert(event.error.message); }); self.map.add(layer, index); return layer; }); }, /** * 添加发布的切片服务 * @param {any} option 地图选项 * @param {any} index 地图图层索引 */ addTileLayer: function(option, index, name, callback) { if (!option) { return } var self = this; require(["esri/layers/TileLayer"], function(TileLayer) { var layer = new TileLayer(option); layer.title = name; //添加图层到视图中执行该代码 layer.on("layerview-create", function() { //将该图层添加到图层中 self._addLayerToLayers(layer.id, layer.title, layer.visible, "tilelayer", layer); if (callback) { callback(); } }); layer.on("layerview-create-error", function(event) { alert(event.error.message); }); self.map.add(layer, index); return layer; }); }, /** * 添加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(); }); }); }, }); /**+++++++++++++++草图编辑相关+++++++++++++++++++*/ JTMapKit.prototype.extend({ _sketchViewModel: function(callback) { var self = this; require([ "esri/layers/GraphicsLayer", "esri/widgets/Sketch/SketchViewModel" ], function(GraphicsLayer, SketchViewModel) { if (!self.layerSketch) { self.layerSketch = new GraphicsLayer(); self.map.add(self.layerSketch); } if (!self.sketchViewModel) { self.sketchViewModel = new SketchViewModel({ layer: self.layerSketch, view: self.mapView }); self.sketchViewModel.on("create", function(event) { if (event.state == "start") { self.layerSketch.removeAll(); //删除全部 } else if (event.state == "complete") {} }); } callback(); }); }, //激活绘制面工具 sketchPolygonTools: function() { var self = this; this._sketchViewModel(function() { self.sketchViewModel.create("polygon", { mode: "click" }); }); }, //前进 sketchRedo: function() { var self = this; this._sketchViewModel(function() { self.sketchViewModel.redo(); }); }, //回退 sketchUndo: function() { var self = this; this._sketchViewModel(function() { self.sketchViewModel.undo(); }); }, //删除全部 sketchDelete: function() { var self = this; this._sketchViewModel(function() { self.layerSketch.removeAll(); //删除全部 }); }, //获取绘制的要素 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 polygon = projection.project(self.sGraphic.geometry, outSpatialReference); //通过计算面积判断该Polygon是否为反序 var result = geodesicUtils.geodesicAreas([polygon], "square-meters"); var area = parseFloat(result[0]); //如果初次计算的面积小于0 说明坐标串是反序的 将其反过来 重新计算 //if (area > 0) { // polygon.rings[0].reverse(); //} var resCoords = ""; for (var idx = 0; idx < polygon.rings[0] .length; idx++) { var point = polygon.getPoint(0, idx); if (resCoords == "") { resCoords = point.x + "," + point.y; } else { resCoords += "," + point.x + "," + point.y; } } callback(resCoords); }); }); }); } else { //如果没有绘制要素则返回undefined callback(undefined); } } else { callback(undefined); } }, //添加编辑要素 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.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({ _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); } }) }); }, //查询绘制处理事件 _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) { this._showQueryResultPopup(clickPoint, function() { self.mapView.popup.visible = false; self._queryTaskFromGeometry(self.queryTaskGraphic.geometry); self.queryTaskGraphic = undefined; // console.log($('.esri-popup__main-container').parent().html()); }); } } }, /** * 显示测量结果 * @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 } /* 定义一个action试试 */ // var queryAction = { // title: '查询', // id: 'actionQuery', // image: "https://developers.arcgis.com/javascript/latest//sample-code/popup-actions/live/Measure_Distance16.png" // }; // popup.actions.push(queryAction); 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); } }); }, //查询 _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) { //通过回调返回查询到的图元 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); }); } }); } ); }, //点击查询 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); }, //多边形查询 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); }, //矩形查询 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); } }) /**+++++++++++++++测量相关+++++++++++++++++++++++*/ 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); }); }); }, //绘制处理事件 _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); }); } else { this._measureAddText('起点', clickPoint); } } else if (mGeometry.type == "polygon") { if (mGeometry.rings[0].length >= 3) { this._measureLengthOrAreaOrCoord(function(result) { self._showMeasureResultPopup("面积测量结果", result, clickPoint); }); } else if (mGeometry.rings[0].length == 1) { this._measureAddText('起点', clickPoint); } } else if (mGeometry.type == "point") { this._measureLengthOrAreaOrCoord(function(result) { self._showMeasureResultPopup("当前位置坐标", result, clickPoint); }); } }, /** * 添加文字 * @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.toLocaleLowerCase() == layerName.toLocaleLowerCase()) { layer.visible = isVisible; return idx; } }); }, /** 获取地图中的所有图层 */ getLayers: function() { var self = this; if (self.loadLayers) { return self.loadLayers; } }, /** * 根据图层ID查找图层 * @param {any} layerID */ findLayer: function(layerID) { var self = this; if (self.map) { return self.map.findLayerById(layerID) } return undefined; }, /** * 删除指定的图层 * @param {any} layer 图层集合中的图层 */ removeLayer: function(layer) { var self = this; if (self.map) { return self.map.remove(layer); } return undefined; }, /** * 设置图层可见及不可见 * @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 {Object} layerName * @param {Object} visible */ setVisibleByName: function(layerName, visible) { var self = this; for (var i = 0; i < self.loadLayers.length; i++) { var layer = self.loadLayers[i]; if (layer.title == layerName) { layer.slayer.findSublayerById(layer.id).visible = visible; } } }, }); /**++++++++++++其他相关内容++++++++++++++++++++++*/ JTMapKit.prototype.extend({ /** 删除临时绘制的所有内容 */ DeleteTempDraw: function() { if (this.layerSketch) { this.layerSketch.removeAll(); } this.clearGraphic(); }, /** * 地图输出 * @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; } ); } });