wangrong
2021-12-20 f07ba16e02cf0962c88223d7c9c8875bf35344be
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
"use script"; //开发环境建议开启严格模式
(function (window, mars3d) {
  //创建widget类,需要继承BaseWidget
  class MyWidget extends mars3d.widget.BaseWidget {
    //外部资源配置
    get resources() {
      return [
        "js/getGraphicDefStyle.js",
        "./lib/kml/kml-geojson.js", //导出kml支持,不用kml时可以删除
        "./lib/dom2img/dom-to-image.js", //字体标号使用到的div转img库,无此标号时可以删除
      ];
    }
 
    //弹窗配置
    get view() {
      return {
        type: "window",
        url: "view.html",
        windowOptions: {
          width: 250,
          position: {
            top: 50,
            right: 5,
            bottom: 5,
          },
        },
      };
    }
 
    //初始化[仅执行1次]
    create() {
      this.storageName = "mars3d_plot";
 
      this.graphicGroupLayer = new mars3d.layer.GraphicGroupLayer({
        name: this.config.name,
        pid: 99, //图层管理 中使用,父节点id
        defaultLayer: "默认分组",
        isRestorePositions: false, //在标绘和编辑结束时,是否将坐标还原为普通值,true: 停止编辑时会有闪烁,但效率要好些。
        hasEdit: false,
      });
      this.map.addLayer(this.graphicGroupLayer);
 
      var that = this;
      this.graphicGroupLayer.bindContextMenu([
        {
          text: "删除对象",
          iconCls: "fa fa-trash-o",
          callback: function (e) {
            let graphic = e.graphic;
            if (graphic) {
              that.deleteEntity(graphic);
            }
          },
        },
      ]);
 
      //事件监听
      this.graphicGroupLayer.on(mars3d.EventType.drawCreated, (e) => {
        this.showLayerTree();
 
        var graphic = e.graphic;
        this.startEditing(graphic);
      });
      //模型加载完成后事件
      this.graphicGroupLayer.on(mars3d.EventType.load, (e) => {
        //console.log('gltf模型加载完成');
        haoutil.loading.hide();
      });
      this.graphicGroupLayer.on(mars3d.EventType.editStart, (e) => {
        var graphic = e.graphic;
        this.startEditing(graphic);
      });
      this.graphicGroupLayer.on(mars3d.EventType.editMovePoint, (e) => {
        var graphic = e.graphic;
        this.startEditing(graphic);
      });
      this.graphicGroupLayer.on(mars3d.EventType.editRemovePoint, (e) => {
        var graphic = e.graphic;
        this.startEditing(graphic);
      });
      this.graphicGroupLayer.on(mars3d.EventType.editStop, (e) => {
        var graphic = e.graphic;
        this.stopEditing();
 
        this.sendSaveEntity(graphic); //保存数据
        this.showLayerTree();
      });
 
      this.graphicGroupLayer.on(mars3d.EventType.updateAttr, (e) => {
        var graphic = e.graphic;
        //更新了名称
        if (e.attr.name && this.viewWindow) {
          this.viewWindow.treeWork.updateNode(graphic);
        }
      });
 
      this.graphicGroupLayer.on(mars3d.EventType.popupOpen, (event) => {
        let container = event.container;
        let btnOk = container.querySelector(".mars3d-popup-btn");
        if (btnOk) {
          let graphic = event.graphic;
          btnOk.addEventListener("click", (e) => {
            $(".mars3d-popup-edititem").each(function () {
              var val = $(this).val();
              var key = $(this).attr("data-type");
              graphic.attr[key] = val;
            });
            this.map.closePopup();
          });
        }
      });
 
      this.sendGetList();
    }
    //每个窗口创建完成后调用
    winCreateOK(opt, result) {
      this.viewWindow = result;
    }
    //激活插件
    activate() {
      this.graphicGroupLayer.hasEdit = true;
    }
    //释放插件
    disable() {
      this.stopEditing();
 
      this.graphicGroupLayer.stopDraw();
      this.graphicGroupLayer.hasEdit = false;
 
      this.viewWindow = null;
    }
    getDefStyle(type) {
      return getGraphicDefStyle(type);
    }
    updateTemplateValues(url) {
      if (this.map.options.templateValues) {
        return mars3d.Util.template(url, this.map.options.templateValues);
      } else {
        return url;
      }
    }
    hasEdit(val) {
      this.graphicGroupLayer.hasEdit = val;
    }
    hasPopup(val) {
      if (val) {
        this.graphicGroupLayer.bindPopup((event) => {
          let graphic = event.graphic;
          var html = mars3d.Util.getTemplateHtml({
            title: "属性编辑",
            template: [
              { field: "name", name: "名称" },
              { field: "address", name: "地址" },
              { field: "phone", name: "电话" },
              { field: "remark", name: "备注", type: "textarea" },
              { name: "确定", type: "button" },
            ],
            attr: graphic.attr,
            edit: true,
            width: 190,
          });
          return html;
        });
      } else {
        this.graphicGroupLayer.unbindPopup();
      }
    }
    //开始标记
    startDraw(defval) {
      haoutil.loading.hide();
      switch (defval.type) {
        default:
          break;
        case "model": //小模型
          defval.drawShow = true; //模型点状对象绘制时,是否显示本身对象,可避免在3dtiles上拾取坐标存在问题。
          haoutil.loading.show(); //LoadEnd后关闭
          break;
        case "point":
        case "font-point":
        case "billboard":
          defval.drawShow = true; //模型点状对象绘制时,是否显示本身对象,可避免在3dtiles上拾取坐标存在问题。
          break;
      }
 
      console.log("开始绘制", JSON.stringify(defval));
      this.graphicGroupLayer.startDraw(defval);
    }
    //结束绘制、等同双击完成绘制,比如手机端无法双击结束
    endDraw() {
      this.graphicGroupLayer.endDraw();
    }
    startEditingById(id) {
      var graphic = this.graphicGroupLayer.getGraphicById(id);
      if (graphic == null) {
        return;
      }
      graphic.flyTo();
 
      this.graphicGroupLayer.startEditing(graphic);
    }
    startEditing(graphic) {
      clearTimeout(this.timeTik);
 
      if (this.viewWindow == null) {
        return;
      }
 
      var plotAttr = mars3d.widget.getClass("widgets/plotAttr/widget.js");
      if (plotAttr && plotAttr.isActivate) {
        plotAttr.startEditing(graphic, graphic.coordinates);
      } else {
        mars3d.widget.activate({
          uri: "widgets/plotAttr/widget.js",
          graphic: graphic,
          lonlats: graphic.coordinates,
        });
      }
    }
    stopEditing() {
      this.timeTik = setTimeout(function () {
        mars3d.widget.disable("widgets/plotAttr/widget.js");
      }, 200);
    }
 
    flyTo(target) {
      //参数解释:线面数据:scale控制边界的放大比例,点数据:radius控制视距距离
      this.map.flyToGraphic(target, { scale: 1.9, radius: 1000 });
    }
    //文件处理
    getGeoJson(target) {
      if (target) {
        return target.toGeoJSON();
      } else {
        return this.graphicGroupLayer.toGeoJSON();
      }
    }
    downloadJson(filename, target) {
      var data = this.getGeoJson(target);
      if (data == null || (data.features && data.features.length == 0)) {
        haoutil.msg("当前未标绘任何数据!");
      } else {
        var timestr = new Date().format("MMddHHmmss");
        haoutil.file.downloadFile(filename + "_" + timestr + ".json", JSON.stringify(data));
      }
    }
 
    toKml(target) {
      var geojsonObject = this.getGeoJson(target);
      if (geojsonObject == null) {
        return null;
      }
 
      geojsonObject = haoutil.system.clone(geojsonObject);
 
      var kml = kgUtil.toKml(geojsonObject, {
        name: "Mars3D标绘数据",
        documentName: "Mars3D标绘数据文件",
        documentDescription: "标绘数据 by mars3d.cn",
        simplestyle: true,
      });
 
      return kml;
    }
    downloadKml(filename, target) {
      var data = this.toKml(target);
      if (data == null) {
        haoutil.msg("当前未标绘任何数据!");
      } else {
        var timestr = new Date().format("MMddHHmmss");
        haoutil.file.downloadFile(filename + "_" + timestr + ".kml", data);
      }
    }
    loadGeoJSON(json, options) {
      if (json == null) {
        return;
      }
      var arr = this.graphicGroupLayer.loadGeoJSON(json, options);
 
      //本地存储
      localforage.setItem(this.storageName, json);
 
      this.showLayerTree();
 
      return arr;
    }
    deleteAll() {
      this.stopEditing();
      this.graphicGroupLayer.clear();
      this.sendDeleteAll();
      this.showLayerTree();
    }
    deleteEntity(graphic) {
      graphic.remove();
 
      this.sendDeleteEntity(graphic); //保存数据
      this.showLayerTree();
    }
    //搜索
    query(text, maxcount) {
      var arrGraphic = this.graphicGroupLayer.getGraphics();
 
      var arr = [];
      var counts = 0;
      for (var i = 0; i < arrGraphic.length; i++) {
        var graphic = arrGraphic[i];
 
        var name;
        if (graphic.type == "label") {
          name = graphic.text;
        } else if (graphic.attr?.name) {
          name = graphic.attr.name;
        }
 
        if (name == null || name.indexOf(text) == -1) {
          continue;
        }
 
        arr.push({
          name: name,
          type: "标绘 - " + name,
          _datatype: "plot",
          _entity: graphic,
        });
 
        if (maxcount) {
          counts++;
          if (counts > maxcount) {
            break;
          }
        }
      }
      return arr;
    }
    //弹窗属性编辑处理
    // showEditAttrWindow(param) {
    //   this.last_window_param = param
 
    //   layer.open({
    //     type: 2,
    //     title: '选择数据',
    //     fix: true,
    //     shadeClose: false,
    //     maxmin: true,
    //     area: ['100%', '100%'],
    //     content: 'test.html?name=' + param.attrName + '&value=' + param.attrVal,
    //     skin: 'layer-mars-dialog animation-scale-up',
    //     success: function (layero) {},
    //   })
    // }
    // saveWindowEdit(attrVal) {
    //   this.viewWindow.plotEdit.updateAttr(this.last_window_param.parname, this.last_window_param.attrName, attrVal)
    //   layer.close(layer.index)
    // }
 
    //分组树相关方法
    showLayerTree() {
      if (!this.viewWindow || !this.isActivate) {
        return;
      }
      this.viewWindow.treeWork.loadData(this.graphicGroupLayer.getLayers());
 
      this.sendSaveEntity(); //保存所有数据
    }
    checkRemoveGroup(layer) {
      if (this.graphicGroupLayer.length < 2) {
        haoutil.msg("不能删除所有图层,需要至少保留1个图层!");
        return false;
      }
      return true;
    }
    deleteLayer(layer) {
      var result = this.graphicGroupLayer.deleteLayer(layer);
      if (result) {
        this.showLayerTree();
        haoutil.msg("删除成功!");
        return true;
      } else {
        haoutil.msg("删除失败!");
        return false;
      }
    }
    //删除所有非空数组
    deleteEmptyLayer() {
      if (this.graphicGroupLayer.length < 2) {
        haoutil.msg("不能删除所有图层,需要至少保留1个图层!");
        return;
      }
      this.graphicGroupLayer.deleteEmptyLayer();
      this.showLayerTree();
    }
    editGroupName(layer) {
      mars3d.widget.activate({
        uri: "widgets/plotGroupName/widget.js",
        name: layer ? "重命名分组" : "新增分组",
        data: layer ? layer.name : "",
        checkName: (newname) => {
          //校验分组是否有同名的
          return this.graphicGroupLayer.hasLayer(newname, layer);
        },
        callback: (newname) => {
          // console.log(newname)
 
          if (layer) {
            //修改
            layer.name = newname;
          } else {
            //新增
            this.graphicGroupLayer.createLayer(newname);
          }
          this.showLayerTree();
        },
      });
    }
    changeSelectedLayer(layer) {
      this.graphicGroupLayer.selectedLayer = layer;
      this.showLayerTree();
    }
    moveToLayer(graphic, group) {
      this.graphicGroupLayer.moveToLayer(graphic, group);
      this.showLayerTree();
    }
    //数据保存及加载处理
    sendGetList() {
      if (window.hasServer) {
        //读取后台存储
        // window.sendAjax({
        //   url: 'map/plot/list',
        //   type: 'get',
        //   success: (arr) => {
        //     var arrjson = []
        //     for (var i = 0; i < arr.length; i++) {
        //       var geojson = JSON.parse(arr[i].geojson)
        //       geojson.properties.id = arr[i].id
        //       arrjson.push(geojson)
        //     }
        //     this.loadGeoJSON({ type: 'FeatureCollection', features: arrjson }, {  clear: true,  flyTo: true })
        //   },
        // })
      } else {
        //读取本地存储
        localforage.getItem(this.storageName).then((laststorage) => {
          if (laststorage == null || laststorage == "null") {
            this.loadDemoData();
          } else {
            console.log("加载历史缓存数据", laststorage);
            this.loadGeoJSON(laststorage, { clear: true, flyTo: true });
          }
        });
      }
    }
    sendSaveEntity(graphic) {
      if (this.viewWindow == null) {
        return;
      }
      console.log("plot: 保存了数据");
 
      if (window.hasServer) {
        //服务端存储
        // if (!graphic.attr.name) {
        //   haoutil.msg('名称不可为空!')
        //   return
        // }
        // let geojson = graphic.toGeoJSON()
        // window.sendAjax({
        //   url: 'map/plot/update',
        //   type: 'post',
        //   data: {
        //     id: graphic.id,
        //     name: graphic.attr.name || '', //名称
        //     geojson: geojson || '', //geojson
        //   },
        //   contentType: 'application/json',
        //   success: function (data) {
        //     graphic.id = data.id
        //   },
        // })
      } else {
        //本地存储
        localforage.setItem(this.storageName, this.getGeoJson());
      }
 
      //测试的功能
      //this.sendSocket(graphic)
    }
    sendDeleteEntity(graphic) {
      // console.log('plot: 删除了数据')
 
      if (window.hasServer) {
        //后台删除
        // window.sendAjax({
        //   url: 'map/plot/' + graphic.id,
        //   type: 'delete',
        //   contentType: 'application/json',
        //   success: function (result) {},
        // })
      } else {
        localforage.setItem(this.storageName, this.getGeoJson());
      }
    }
    sendDeleteAll() {
      // console.log('plot: 删除了所有数据')
 
      if (window.hasServer) {
        //后台删除
        // window.sendAjax({
        //   url: 'map/plot/deleteAll',
        //   contentType: 'application/json',
        //   success: function (result) {},
        // })
      } else {
        //本地存储
        localforage.removeItem(this.storageName);
      }
    }
 
    //websocket更新坐标
    // socketConfig() {
    //   var that = this
    //   mars3d.widget.activate({
    //     uri: 'widgets/plotSocket/widget.js',
    //     updateAttr: function (json) {
    //       that.graphicGroupLayer.loadGeoJSON(json)
    //     },
    //   })
    // }
    // sendSocket(graphic) {
    //   var plotSocket = mars3d.widget.getClass('widgets/plotSocket/widget.js')
    //   if (plotSocket && plotSocket.isActivate) {
    //     plotSocket.sendSocket(graphic.toGeoJSON())
    //   }
    // }
 
    //实际系统时可以注释下面代码,该代码是mars3d官网在线加载演示数据
    loadDemoData() {
      if (window.location.hostname.indexOf("mars") == -1) {
        return;
      }
 
      $.getJSON("//data.mars3d.cn/file/geojson/mars3d-draw.json", (result) => {
        if (!this.isActivate) {
          return;
        }
        this.loadGeoJSON(result, { clear: true, flyTo: true });
      });
    }
  }
 
  //注册到widget管理器中。
  mars3d.widget.bindClass(MyWidget);
 
  //每个widet之间都是直接引入到index.html中,会存在彼此命名冲突,所以闭包处理下。
})(window, mars3d);