tileLayer.wmts.realtime.js 64 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920921922923924925926927928929930931932933934935936937938939940941942943944945946947948949950951952953954955956957958959960961962963964965966967968969970971972973974975976977978979980981982983984985986987988989990991992993994995996997998999100010011002100310041005100610071008100910101011101210131014101510161017101810191020102110221023102410251026102710281029103010311032103310341035103610371038103910401041104210431044104510461047104810491050105110521053105410551056105710581059106010611062106310641065106610671068106910701071107210731074107510761077107810791080108110821083108410851086108710881089109010911092109310941095109610971098109911001101110211031104110511061107110811091110111111121113111411151116111711181119112011211122112311241125112611271128112911301131113211331134113511361137113811391140114111421143114411451146114711481149115011511152115311541155115611571158115911601161116211631164116511661167116811691170117111721173117411751176117711781179118011811182118311841185118611871188118911901191119211931194119511961197119811991200120112021203120412051206120712081209121012111212121312141215121612171218121912201221122212231224122512261227122812291230123112321233123412351236123712381239124012411242124312441245124612471248124912501251125212531254125512561257125812591260126112621263126412651266126712681269127012711272127312741275127612771278127912801281128212831284128512861287128812891290129112921293129412951296129712981299130013011302130313041305130613071308130913101311131213131314131513161317131813191320132113221323132413251326132713281329133013311332133313341335133613371338133913401341134213431344134513461347134813491350135113521353135413551356135713581359136013611362136313641365136613671368136913701371137213731374137513761377137813791380138113821383138413851386138713881389139013911392139313941395139613971398139914001401140214031404140514061407140814091410141114121413141414151416141714181419142014211422142314241425142614271428142914301431143214331434143514361437143814391440144114421443144414451446144714481449145014511452145314541455145614571458145914601461146214631464146514661467146814691470147114721473147414751476147714781479148014811482148314841485148614871488148914901491149214931494149514961497149814991500150115021503150415051506150715081509151015111512151315141515151615171518151915201521152215231524152515261527152815291530153115321533153415351536153715381539154015411542154315441545154615471548154915501551155215531554155515561557155815591560156115621563156415651566156715681569157015711572157315741575157615771578157915801581158215831584158515861587158815891590159115921593159415951596159715981599160016011602160316041605160616071608160916101611161216131614161516161617161816191620162116221623162416251626162716281629163016311632163316341635163616371638163916401641164216431644164516461647
  1. window.getMarkerPopup = function (attr) {
  2. let shiptype = attr.attributes.shiptype;
  3. if (attr.attributes.shipType) {
  4. shiptype = attr.attributes.shipType;
  5. }
  6. if (!shiptype) {
  7. shiptype = "未知"
  8. }
  9. let englishName = attr.attributes.englishName ? attr.attributes.englishName : "-"
  10. let MMSI = attr.attributes._targetID ? attr.attributes._targetID : "-"
  11. let name = attr.name ? attr.name : "-"
  12. let countryname = attr.attributes.countryname ? attr.attributes.countryname : "-"
  13. let time = '-'
  14. if( typeof attr.time === 'number' ){
  15. if((attr.time+"").length === 10 ){
  16. time = formatDate(attr.time * 1000)
  17. }else if((attr.time+"").length === 13){
  18. time = formatDate(attr.time)
  19. }
  20. }else if(typeof attr.time === 'string'){
  21. if(attr.time.length === 10 ){
  22. time = formatDate(parseInt(attr.time) * 1000)
  23. }else if(attr.time.length === 13){
  24. time = formatDate(parseInt(attr.time))
  25. }
  26. }
  27. let speed = attr.attributes.speed ? attr.attributes.speed : "-"
  28. let course = attr.attributes.course ? attr.attributes.course : "-"
  29. var html = "<div class='ship-ss-pop'>"
  30. + "<span>MMSI:" + MMSI + "</span></br>"
  31. + "<span>名称:" + name + "</span></br>"
  32. + "<span>英文名称:" + englishName + "</span></br>"
  33. + "<span>国籍:" + countryname + "</span></br>"
  34. + "<span>类型:" + shiptype + "</span></br>"
  35. + "<span>经度:" + attr.lon + "</span></br>"
  36. + "<span>纬度:" + attr.lat + "</span></br>"
  37. + "<span>更新时间:" + time + "</span></br>"
  38. + "<span>转向:" + course + "</span></br>" //1:雷达;2:AIS 3:ADSB 4:北斗 5:GPS
  39. + "<span>来源:" + (attr.attributes.dataflag == 1 ? '雷达' : attr.attributes.dataflag == 2 ? 'AIS' : attr.attributes.dataflag == 3 ? 'ADSB' : attr.attributes.dataflag == 4 ? '北斗' : attr.attributes.dataflag == 5 ? 'GPS' : attr.layerCnName) + "</span></br>"
  40. + "<span>速度:" + speed + "</span></br>"
  41. + "</div>"
  42. return html;
  43. }
  44. // let websocket_layername = { "zt_cbzt_kyc_ss": true, "zt_cbzt_hc_ss": true, "zt_cbzt_yc_ss": true, "zt_cbzt_qt_ss": true, "zt_cbzt_ld_ss": true, "zt_cbzt_sw_ss": true, "zt_cbzt_wz_ss": true, "zt_cbzt_gz_ss": true, "zt_cbzt_tc_ss": true, "zt_cbzt_yhc_ss": true, "zt_cbzt_gc_ss": true };
  45. let websocket_layername = { "cz_czlltc_wgy":true,"zt_cbzt_kyc_ss": true, "zt_cbzt_hc_ss": true, "zt_cbzt_yc_ss": true, "zt_cbzt_qt_ss": true, "zt_cbzt_ld_ss": true, "zt_cbzt_sw_ss": true, "zt_cbzt_wz_ss": true, "zt_cbzt_gz_ss": true, "zt_cbzt_tc_ss": true, "zt_cbzt_yhc_ss": true, "zt_cbzt_gc_ss": true };
  46. let loadYJLayer = {};
  47. L.TileLayer.WMTS.REALTIME = L.TileLayer.WMTS.extend({
  48. options: {
  49. tileSize: 256,
  50. realtimeLayer: '',
  51. gjLayer: '',
  52. showrealtimelevel: 14,
  53. showLabellevel: 14,
  54. markerPopup: window.getMarkerPopup,
  55. time: 600,
  56. ObjType: '2',
  57. pointX:130,
  58. pointY:315,
  59. // websocketUrl : 'ws://localhost:8084/websocket/'
  60. websocketUrl: 'ws://10.110.35.104/websocket/'
  61. // websocketUrl : 'ws://10.110.35.88:8080/websocket/'
  62. },
  63. realtimeMarkerLayerGroup: {},
  64. realtimeHander: [],
  65. removeOutTimeHander: [],
  66. realtimeIcon: {},
  67. markerGroup: {},
  68. moveendHander: null,
  69. zoomendHander: null,
  70. realtimeGJLayer: {},
  71. markerDrawJ: null,
  72. pupopOpenHander: null,
  73. gjLayer: {},
  74. gjPaly: {},
  75. eventMap: {},
  76. messageType: "",
  77. realtimeWebsocket: null,
  78. realtimeParam: "",
  79. wgyInfoMap : new Map(),
  80. initialize: function (url, jsonUrl, options, markerClick) { // (String, Object)
  81. // options.sessionToken = window.sessionToken;
  82. this._jsonUrl = jsonUrl;
  83. this._url = url;
  84. this.markerClick = markerClick
  85. var wmtsParams = L.extend({}, this.defaultWmtsParams);
  86. var tileSize = options.tileSize || this.options.tileSize;
  87. if (options.detectRetina && L.Browser.retina) {
  88. wmtsParams.width = wmtsParams.height = tileSize * 2;
  89. } else {
  90. wmtsParams.width = wmtsParams.height = tileSize;
  91. }
  92. for (var i in options) {
  93. // all keys that are not TileLayer options go to WMTS params
  94. if (!this.options.hasOwnProperty(i) && i != "matrixIds" && i != "jsonUrl") {
  95. wmtsParams[i] = options[i];
  96. }
  97. }
  98. this.wmtsParams = wmtsParams;
  99. this.matrixIds = options.matrixIds || this.getDefaultMatrix();
  100. if (!options.zIndex || options.zIndex < 10) {
  101. options.zIndex = 10;
  102. }
  103. L.setOptions(this, options);
  104. this.realtimeMarkerLayerGroup.curZoom = window.map.getZoom();
  105. this.realtimeMarkerLayerGroup.realtimeLayerGroup = L.layerGroup().addTo(window.map);
  106. this.realtimeGJLayer.layerGroup = L.layerGroup().addTo(window.map);
  107. this.gjLayer.layerGroup = L.layerGroup().addTo(window.map);
  108. this.markerDrawJ = L.layerGroup().addTo(window.map);
  109. this.gjLayer.gjPoyline = {};
  110. this.gjLayer.gjCircleMarker = {};
  111. this.gjLayer.seMarker = {};
  112. this.realtimeGJLayer.gj = {};
  113. this.realtimeGJLayer.ssgjOnMap = {};
  114. this.currentRealTimeListObj = {}
  115. var _this = this;
  116. this.eventMap = {
  117. click: function (ev) { },
  118. moveend: function (ev) {
  119. if (_this.moveendHander) {
  120. clearTimeout(_this.moveendHander);
  121. }
  122. _this.moveendHander = setTimeout(function () {
  123. _this.removeOutBounds();
  124. }, 500);
  125. },
  126. zoomend: function (ev) {
  127. if (_this.zoomendHander) {
  128. clearTimeout(_this.zoomendHander);
  129. }
  130. _this.zoomendHander = setTimeout(function () {
  131. _this.realtimeUpdate();
  132. }, 500);
  133. }
  134. };
  135. window.map.on(this.eventMap);
  136. /*window.map.on('moveend', function(ev) {
  137. //console.log("....."+ev);
  138. if(_this.moveendHander){
  139. clearTimeout(_this.moveendHander);
  140. }
  141. _this.moveendHander = setTimeout(function(){
  142. _this.removeOutBounds();
  143. //_this.realtimeUpdate();
  144. },1000);
  145. //_this.markerLayerGroup = L.marker(ev.latlng,{iconUrl:'images/marker-icon-2x.png'}).addTo(map);
  146. });*/
  147. /*window.map.on('zoomend', function(ev) {
  148. _this.realtimeUpdate();
  149. });*/
  150. //window.gjThis = this;
  151. //window.goOpenGJ = this.goOpenGJ;
  152. if (this.realtimeHander && this.realtimeHander.length > 0) {
  153. for (var i in this.realtimeHander) {
  154. clearInterval(this.realtimeHander[i]);
  155. }
  156. }
  157. this.clearMarker();
  158. var _this = this;
  159. this.realtimeHander.push(setInterval(function () {
  160. if (_this.messageType == "http") {
  161. _this.realtimeUpdate();
  162. }
  163. }, 1000));
  164. this.removeOutTimeHander.push(setInterval(function () {
  165. _this.removeOutTime()
  166. }, 1000));
  167. },
  168. // @method createTile(coords: Object, done?: Function): HTMLElement
  169. // Called only internally, overrides GridLayer's [`createTile()`](#gridlayer-createtile)
  170. // to return an `<img>` HTML element with the appropiate image URL given `coords`. The `done`
  171. // callback is called when the tile has been loaded.
  172. createTile: function (coords, done) {
  173. var tile = document.createElement('img');
  174. L.DomEvent.on(tile, 'load', L.bind(this._tileOnLoad, this, done, tile));
  175. L.DomEvent.on(tile, 'error', L.bind(this._tileOnError, this, done, tile));
  176. if (this.options.crossOrigin) {
  177. tile.crossOrigin = '';
  178. }
  179. /*
  180. Alt tag is set to empty string to keep screen readers from reading URL and for compliance reasons
  181. http://www.w3.org/TR/WCAG20-TECHS/H67
  182. */
  183. tile.alt = '';
  184. /*
  185. Set role="presentation" to force screen readers to ignore this
  186. https://www.w3.org/TR/wai-aria/roles#textalternativecomputation
  187. */
  188. if (coords.z < this.options.showrealtimelevel) {
  189. tile.setAttribute('role', 'presentation');
  190. tile.src = this.getTileUrl(coords);
  191. this.clearMarker();
  192. } else {
  193. tile.src = "";
  194. //window.map.removeLayer(this);
  195. this.realtimeUpdate();
  196. }
  197. return tile;
  198. },
  199. sendRemoveLayerMsg: function () {
  200. if (this.realtimeWebsocket) {
  201. //发送消息后台删除相应的图层
  202. let deleteParam = this.getParam();
  203. deleteParam.deletelayername = this.options.realtimeLayer
  204. this.realtimeParam = JSON.stringify(deleteParam);
  205. this.sendWebsocketMsg();
  206. //this.realtimeWebsocket.close();
  207. this.realtimeWebsocket = null;
  208. // window.realtimeWebsocketHandle[this.options.realtimeLayer] = null;
  209. if (window.realtimeWebsocketHandle[this.options.realtimeLayer]) {
  210. delete window.realtimeWebsocketHandle[this.options.realtimeLayer];
  211. }
  212. /*if(!window.realtimeWebsocketHandle || Object.keys(window.realtimeWebsocketHandle).length <= 0 ){
  213. window.realtimeWebsocket.close();
  214. window.realtimeWebsocketCreated =null;
  215. window.realtimeWebsocket = null;
  216. }*/
  217. }
  218. },
  219. onRemove: function (map) {
  220. //map.removeLayer(this); this.yjHander
  221. this.sendRemoveLayerMsg();
  222. if (this.realtimeHander && this.realtimeHander.length > 0) {
  223. for (var i in this.realtimeHander) {
  224. clearInterval(this.realtimeHander[i]);
  225. this.realtimeHander[i] = null;
  226. }
  227. this.realtimeHander = [];
  228. }
  229. if (this.removeOutTimeHander && this.removeOutTimeHander.length > 0) {
  230. for (var i in this.removeOutTimeHander) {
  231. clearInterval(this.removeOutTimeHander[i]);
  232. this.removeOutTimeHander[i] = null;
  233. }
  234. this.removeOutTimeHander = [];
  235. }
  236. /* for (var k in this.markerGroup) {
  237. let m = this.markerGroup[k];
  238. this.removeMarker(k);
  239. m = null;
  240. }*/
  241. this.clearMarker();
  242. window.map.off(this.eventMap);
  243. L.TileLayer.WMTS.prototype.onRemove.call(this, map);
  244. },
  245. clearMarker: function () {
  246. //this.realtimeMarkerLayerGroup.realtimeLayerGroup.clearLayers();
  247. for (let i in this.markerGroup) {
  248. this.removeMarker(i);
  249. }
  250. this.markerGroup = {};
  251. this.realtimeGJLayer.layerGroup.clearLayers();
  252. this.realtimeGJLayer.gj = {};
  253. this.realtimeGJLayer.gjCircleMarker = {};
  254. this.markerDrawJ.clearLayers();
  255. },
  256. removeMarker: function (id) {
  257. if (this.markerGroup[id]) {
  258. if (this.markerGroup[id]._icon) {
  259. L.DomUtil.remove(this.markerGroup[id]._icon);
  260. }
  261. console.log(this.markerGroup[id].attributes.realtimeLayer);
  262. this.realtimeMarkerLayerGroup.realtimeLayerGroup.removeLayer(this.markerGroup[id]);
  263. delete this.markerGroup[id];
  264. }
  265. if (this.realtimeGJLayer.gj[id]) {
  266. this.realtimeGJLayer.layerGroup.removeLayer(this.realtimeGJLayer.gj[id]);
  267. delete this.realtimeGJLayer.gj[id];
  268. }
  269. if (this.realtimeGJLayer.gjCircleMarker[id]) {
  270. this.realtimeGJLayer.layerGroup.removeLayer(this.realtimeGJLayer.gjCircleMarker[id]);
  271. delete this.realtimeGJLayer.gjCircleMarker[id];
  272. }
  273. },
  274. removeOutTime: function () {
  275. var datatime = Math.ceil(new Date().getTime() / 1000) - this.options.time;
  276. var m;
  277. var size = 0
  278. for (var k in this.markerGroup) {
  279. m = this.markerGroup[k];
  280. if (m.attributes && parseInt(m.attributes.time) < datatime) {
  281. this.removeMarker(k);
  282. m = null;
  283. }
  284. size++;
  285. }
  286. console.log(this.options.realtimeLayer, ":", size);
  287. },
  288. removeOutBounds: function () {
  289. var bound = window.map.getBounds();
  290. var m;
  291. for (var k in this.markerGroup) {
  292. m = this.markerGroup[k];
  293. if (!bound.contains(m.getLatLng())) {
  294. this.removeMarker(k);
  295. m = null;
  296. }
  297. }
  298. },
  299. getFanweiConfig: function () {
  300. var minx = window.map.getBounds().getSouthWest().lng
  301. , maxx = window.map.getBounds().getNorthEast().lng
  302. , miny = window.map.getBounds().getSouthWest().lat
  303. , maxy = window.map.getBounds().getNorthEast().lat;
  304. var options = this.options
  305. var fanweiConfig = ''
  306. if (options.point) {
  307. fanweiConfig = this.getParamString({
  308. point: options.point,
  309. radius: options.radius
  310. })
  311. } else if (options.polygon) {
  312. fanweiConfig = this.getParamString({
  313. polygon: options.polygon
  314. })
  315. } else if (options.bbox) {
  316. fanweiConfig = this.getParamString({
  317. bbox: options.bbox
  318. })
  319. } else {
  320. fanweiConfig = "?bbox=" + encodeURIComponent("BBOX(" + minx + "," + maxx + "," + maxy + "," + miny + ")")
  321. }
  322. fanweiConfig = '&' + fanweiConfig.substr(1)
  323. return fanweiConfig
  324. },
  325. clearSsgjOnMap: function (shipId) {
  326. var obj = this.realtimeGJLayer.ssgjOnMap[shipId]
  327. if (!obj) {
  328. return
  329. }
  330. if (obj.line) {
  331. this.realtimeGJLayer.layerGroup.removeLayer(obj.line);
  332. delete obj.line
  333. }
  334. if (obj.point) {
  335. obj.point.forEach((e) => {
  336. this.realtimeGJLayer.layerGroup.removeLayer(e);
  337. })
  338. delete obj.point
  339. }
  340. },
  341. setSsgjOnMapStatus: function (shipId, val) { // 设置实时图标是否进行轮询记录
  342. var status = !!val
  343. var obj = this.realtimeGJLayer.ssgjOnMap[shipId]
  344. if (!obj) {
  345. this.realtimeGJLayer.ssgjOnMap[shipId] = {}
  346. obj = this.realtimeGJLayer.ssgjOnMap[shipId]
  347. }
  348. this.realtimeGJLayer.ssgjOnMap[shipId].on = status
  349. if (status) {
  350. this.setMarkerSsgjOnMap(shipId)
  351. } else {
  352. this.clearSsgjOnMap(shipId)
  353. }
  354. },
  355. setMarkerSsgjOnMap: function (shipId) { // 记录轮询时图标的点位和线段,形成轨迹
  356. var ship = this.currentRealTimeListObj[shipId]
  357. var obj = this.realtimeGJLayer.ssgjOnMap[shipId]
  358. if (obj && obj.on) {
  359. var point = L.circleMarker([ship.lat, ship.lon], { radius: 3, color: '#00f' })
  360. point.addTo(this.realtimeGJLayer.layerGroup);
  361. if (obj.point && obj.point.length) {
  362. obj.point.push(point)
  363. obj.line.addLatLng([ship.lat, ship.lon])
  364. } else {
  365. obj.line = L.polyline([[ship.lat, ship.lon]], { color: 'red' })
  366. obj.line.addTo(this.realtimeGJLayer.layerGroup)
  367. obj.point = [point]
  368. }
  369. }
  370. },
  371. realtimeUpdate: function (callback) {
  372. if (window.map.getZoom() < this.options.showrealtimelevel || this.gjPaly.isPlay) {
  373. this.sendRemoveLayerMsg();
  374. for (var k in this.markerGroup) {
  375. let m = this.markerGroup[k];
  376. this.removeMarker(k);
  377. m = null;
  378. }
  379. this.clearMarker();
  380. return;
  381. }
  382. /*if( this.realtimeMarkerLayerGroup.curZoom != window.map.getZoom() ){
  383. this.clearMarker();
  384. this.realtimeMarkerLayerGroup.curZoom = window.map.getZoom();
  385. }*/
  386. /*this.wmtsParams.format = "realtimejson";
  387. this.wmtsParams.layer = this.options.realtimeLayer;
  388. this.wmtsParams.tilematrix = window.map.getZoom();*/
  389. // let url = this.getParamString(this.wmtsParams, this._jsonUrl);
  390. // 实时船舶变成三角形图标后的查询接口
  391. /**
  392. * 实时websocket连接对象:
  393. * {
  394. * realtimeWebsocket:
  395. * {
  396. * websocket:new WebSocket("ws://localhost:8080/websocket/{layername}/{filterjson}")
  397. * layername:this.options.realtimeLayer
  398. * param:{bbox:'minx,maxx,maxy,miny'---矩形边界查询条件
  399. * ,cicle:point,radius ----圆圈查询条件,point:圆心,radius:半径
  400. * ,polygon:polygon ----多边形查询条件,polygon:多边形边界坐标
  401. * ,time:10 } ----在线时间,单位秒,10秒
  402. * }
  403. */
  404. if ((this.options.realtimeLayer in websocket_layername)) {
  405. if (this.messageType != "http") {
  406. //websocket连接方式
  407. this.realtimeWebsocket = createWebSocket(this);
  408. }
  409. } else {
  410. this.messageType = "http"
  411. }
  412. if (this.realtimeWebsocket && this.messageType == "websocket") {
  413. if (window.realtimeWebsocketCreated) {
  414. let newParam = JSON.stringify(this.getParam());
  415. if (this.realtimeParam !== newParam) {
  416. this.realtimeParam = newParam;
  417. this.sendWebsocketMsg()
  418. }
  419. }
  420. } else {
  421. this.messageType = "http";
  422. console.log('当前浏览器 Not support websocket');
  423. var datatime = new Date().getTime();
  424. var endTimeSecond = Math.ceil(datatime / 1000)
  425. var startTimeSecond = Math.ceil(datatime / 1000) - this.options.time;
  426. let url = this._jsonUrl + "?format=realtimejson&layer=" + this.options.realtimeLayer + "&tilematrix=" + window.map.getZoom() + this.getFanweiConfig() + "&customsQuery=" + encodeURIComponent("{\"must\":[{\"range\":{\"attributes.collecTime\":{\"lte\":" + endTimeSecond + ",\"gt\":" + startTimeSecond + "}}}]}");
  427. /*if( this.wmtsParams.keyworks ){
  428. url += this.getParamString({
  429. keyworks:this.wmtsParams.keyworks
  430. },url)
  431. }*/
  432. //"107.85003662109375,18.973388671875,111.36566162109375,20.5609130859375"
  433. //bbox:"BBOX(109.6875,111.12671,20.17639,19.44031)",
  434. //BBOX:"BBOX(minx,maxx,maxy,miny)
  435. var _this = this;
  436. window.doXHR(url, function (data) {
  437. _this.realtimeMessageCallback(data, _this);
  438. });
  439. }
  440. },
  441. //发送消息
  442. sendWebsocketMsg: function () {
  443. // console.log(this.realtimeWebsocket,",",this.realtimeWebsocket.ready);
  444. this.realtimeWebsocket.send(this.realtimeParam);
  445. },
  446. getParam: function () {
  447. var options = this.options
  448. var param = {};
  449. param.sessionToken = options.sessionToken;
  450. let bounds = window.map.getBounds();
  451. if (options.point) {
  452. let circle = L.circle(options.point.split(','), { radius: options.radius }).addTo(window.map);
  453. //处理圆圈获取边界报错问题
  454. //circle._project();
  455. bounds = circle.getBounds();
  456. window.map.removeLayer(circle);
  457. // param.cicle = options.point+","+options.radius;
  458. } else if (options.polygon) {
  459. // param.polygon = options.polygon;
  460. let polygonStr = options.polygon.replaceAll('[', '')
  461. .replaceAll('{', '')
  462. .replaceAll('}', '')
  463. .replaceAll(']', '')
  464. .replaceAll('lat:', '')
  465. .replaceAll('lon:', '');
  466. let latlonStr = polygonStr.split(',');
  467. let latlons = [];
  468. for (let i = 0; i < latlonStr.length; i += 2) {
  469. latlons.push([parseFloat(latlonStr[i]), parseFloat(latlonStr[i + 1])]);
  470. }
  471. bounds = L.polygon(latlons).getBounds();
  472. // param.bbox= {minlon:minx,minlat:miny,maxlon:maxx,maxlat:maxy};
  473. // return param;
  474. } else if (options.bbox) {
  475. //"BBOX(110.02455711364746,110.0778579711914,20.0075626373291,19.979496002197266)"
  476. let latlonStr = options.bbox.replaceAll('BBOX(', '').replaceAll(')', '').split(',');
  477. bounds = L.latLngBounds([parseFloat(latlonStr[2]), parseFloat(latlonStr[0])], [parseFloat(latlonStr[3]), parseFloat(latlonStr[1])]);
  478. // param.bbox = options.bbox;
  479. }
  480. var minx = bounds.getSouthWest().lng
  481. , maxx = bounds.getNorthEast().lng
  482. , miny = bounds.getSouthWest().lat
  483. , maxy = bounds.getNorthEast().lat;
  484. param.bbox = { minlon: minx, minlat: miny, maxlon: maxx, maxlat: maxy };
  485. if (options.time) {
  486. param.time = options.time;
  487. } else {
  488. param.time = 10;
  489. }
  490. param.layername = options.realtimeLayer;
  491. return param
  492. },
  493. realtimeMessageCallback: function (data, _this) {
  494. if (data && data.resultList && data.resultList.length && data.resultList.length > 0) {
  495. var icon;
  496. let id;
  497. _this.currentRealTimeListObj = {}
  498. let showTitle = true;
  499. if (window.map.getZoom() < _this.options.showLabellevel) {
  500. showTitle = false;
  501. }
  502. let m;
  503. for (var i in data.resultList) {
  504. if(data.resultList[i].layerAliseName === 'cz_czlltc_wgy'){
  505. let wgyInfo = {}
  506. let id = data.resultList[i].attributes._targetID
  507. if(_this.wgyInfoMap.get(id)){
  508. wgyInfo = _this.wgyInfoMap.get(id)
  509. }else{
  510. wgyInfo = window.getWgyInfoById(id)
  511. _this.wgyInfoMap.set(id,wgyInfo)
  512. }
  513. // let wgyInfo = window.getWgyInfoById(data.resultList[i].attributes._targetID)
  514. data.resultList[i].name = wgyInfo.displayName ? wgyInfo.displayName : "-"
  515. data.resultList[i].attributes.ouDirectory = wgyInfo.ouDirectory ? wgyInfo.ouDirectory : "-"
  516. data.resultList[i].attributes.email = wgyInfo.email ? wgyInfo.email : "-"
  517. data.resultList[i].attributes.ename = wgyInfo.ename ? wgyInfo.ename : "-"
  518. data.resultList[i].attributes.phoneNumber = wgyInfo.phoneNumber ? wgyInfo.phoneNumber : "-"
  519. }
  520. //icon = L.icon({iconUrl: data.resultList[i].markerPath, iconSize: [32, 32],iconAnchor: [16, 8]});
  521. if (_this.options.realtimeLayer != data.resultList[i].layername && _this.options.realtimeLayer != data.resultList[i].layerAliseName) {
  522. console.log(_this.options.realtimeLayer, '....', data.resultList[i].layername);
  523. continue;
  524. }
  525. id = data.resultList[i].attributes._targetID;
  526. _this.currentRealTimeListObj[id] = data.resultList[i]
  527. if (_this.markerGroup[id]) {
  528. //console.log(data.resultList[i].id);
  529. _this.markerGroup[id].attributes = data.resultList[i];
  530. _this.markerGroup[id].attributes.realtimeLayer = _this.options.realtimeLayer;
  531. _this.markerGroup[id].attributes.gjLayer = _this.options.gjLayer;
  532. _this.markerGroup[id].attributes.layername = _this.options.realtimeLayer;
  533. _this.markerGroup[id].off();
  534. if (!_this.markerGroup[id].getLatLng().equals(L.latLng([data.resultList[i].lat, data.resultList[i].lon]))) {
  535. _this.markerGroup[id].updatePosAndIcon(L.latLng([data.resultList[i].lat, data.resultList[i].lon]), data.resultList[i]);
  536. }
  537. _this.markerGroup[id].unbindPopup().bindPopup(_this.options.markerPopup(_this.markerGroup[id].attributes), { autoPan: false, closeButton: false, offset: L.point(_this.options.pointX, _this.options.pointY) });
  538. _this.markerGroup[id].on('click', function () {
  539. _this.markerClick && _this.markerClick({
  540. func: _this.goOpenGJByUrl.bind(_this),
  541. markerInfo: this.attributes
  542. })
  543. }).on('mouseover', function (ev) {
  544. if (_this.pupopOpenHander) {
  545. clearTimeout(_this.pupopOpenHander);
  546. }
  547. _this.pupopOpenHander = setTimeout(function () {
  548. ev.target.openPopup();
  549. }, 500);
  550. if (_this.markerDrawJ) {
  551. if (_this.markerDrawJ.getLayers().length > 0) {
  552. _this.markerDrawJ.getLayers()[0].off();
  553. }
  554. _this.markerDrawJ.clearLayers();
  555. }
  556. let jmarker = L.marker(ev.target.getLatLng(), { icon: new L.AngleIcon({ iconSize: new L.Point(32, 32) }) }).addTo(_this.markerDrawJ);
  557. jmarker.options.icon.drawJ();
  558. jmarker.attributes = this.attributes;
  559. jmarker.off().on('click', function (ev) {
  560. _this.markerClick && _this.markerClick({
  561. func: _this.goOpenGJByUrl.bind(_this),
  562. markerInfo: this.attributes
  563. })
  564. })
  565. });
  566. // 根据ID画线画点,记录到每艘船舶下面,等关闭按钮时统一清除
  567. //_this.realtimeGJLayer.gj[id].addLatLng([data.resultList[i].lat, data.resultList[i].lon]);
  568. //_this.realtimeGJLayer.gjCircleMarker[data.resultList[i].id] = L.circleMarker([data.resultList[i].lat, data.resultList[i].lon],{radius:1,color:data.resultList[i].pcolor}).addTo(_this.realtimeGJLayer.layerGroup);
  569. } else if (!_this.markerGroup[id]) {
  570. //var m = L.marker([data.resultList[i].lat, data.resultList[i].lon],{icon:icon,title:data.resultList[i].attributes._targetID,showTitle:true});
  571. m = L.angleMarker([data.resultList[i].lat, data.resultList[i].lon]
  572. , {
  573. title: data.resultList[i].name
  574. , showTitle: showTitle
  575. , course: data.resultList[i].attributes.course
  576. , speed: data.resultList[i].attributes.speed
  577. , iconUrl: data.resultList[i].markerPath+"?sessionToken="+window.sessionToken
  578. , labelPosition: 'topleft'
  579. });
  580. m.showTitle = showTitle;
  581. m.id = id;
  582. m.attributes = data.resultList[i];
  583. m.attributes.realtimeLayer = _this.options.realtimeLayer;
  584. m.attributes.gjLayer = _this.options.gjLayer;
  585. // m.attributes.layername = _this.options.realtimeLayer;
  586. // console.log(_this.options.markerPopup.apply(_this,m.attributes));
  587. m.bindPopup(_this.options.markerPopup(m.attributes), { autoPan: false, closeButton: false, offset: L.point(_this.options.pointX, _this.options.pointY) }); //autoPanPaddingBottomRight ,,{autoPan:false,closeButton:false,offset:L.point(120,185)}
  588. // var url = _this._jsonUrl+"?format=json&layer="+_this.options.gjLayer+"&customsQuery="+encodeURIComponent("{\"must\":[{\"term\":{\"attributes._targetID\":\""+attr.attributes._targetID+"\"}},{\"range\":{\"attributes.collectime\":{\"lte\":"+endTime+",\"gt\":"+startTime+"}}}]}")+"&sort=collectime:asc";
  589. m.on('click', function () {
  590. _this.markerClick && _this.markerClick({
  591. func: _this.goOpenGJByUrl.bind(_this),
  592. markerInfo: this.attributes
  593. })
  594. })
  595. _this.markerGroup[id] = m;
  596. _this.realtimeMarkerLayerGroup.realtimeLayerGroup.addLayer(_this.markerGroup[id]);
  597. m.on('mouseover', function (ev) {
  598. if (_this.pupopOpenHander) {
  599. clearTimeout(_this.pupopOpenHander);
  600. }
  601. _this.pupopOpenHander = setTimeout(function () {
  602. ev.target.openPopup();
  603. }, 500);
  604. if (_this.markerDrawJ) {
  605. if (_this.markerDrawJ.getLayers().length > 0) {
  606. _this.markerDrawJ.getLayers()[0].off();
  607. }
  608. _this.markerDrawJ.clearLayers();
  609. }
  610. let jmarker = L.marker(ev.target.getLatLng(), { icon: new L.AngleIcon({ iconSize: new L.Point(32, 32) }) }).addTo(_this.markerDrawJ);
  611. jmarker.options.icon.drawJ();
  612. jmarker.attributes = this.attributes;
  613. jmarker.on('click', function (ev) {
  614. _this.markerClick && _this.markerClick({
  615. func: _this.goOpenGJByUrl.bind(_this),
  616. markerInfo: this.attributes
  617. })
  618. })
  619. });
  620. //_this.realtimeGJLayer.gj[id] = L.polyline([[data.resultList[i].lat, data.resultList[i].lon]], {color: 'red'}).addTo(_this.realtimeGJLayer.layerGroup);
  621. // _this.realtimeGJLayer.gjCircleMarker[id] = L.circleMarker([data.resultList[i].lat, data.resultList[i].lon],{radius:1,color:data.resultList[i].pcolor}).addTo(_this.realtimeGJLayer.layerGroup);
  622. }
  623. _this.setMarkerSsgjOnMap(id)
  624. //L.circleMarker([data.resultList[i].lat, data.resultList[i].lon],{radius:1,color:data.resultList[i].pcolor,title:data.resultList[i].attributes._targetID,showTitle:true}).addTo(window.map);
  625. }
  626. }
  627. },
  628. goOpenGJByUrl: function ({ startTime, endTime, targetID }) {
  629. // console.log(startTime,endTime,targetID)
  630. var url = this._jsonUrl + "?format=json&layer=" + this.options.gjLayer + "&customsQuery=" + encodeURIComponent("{\"must\":[{\"term\":{\"attributes._targetID\":\"" + targetID + "\"}},{\"range\":{\"attributes.collecTime\":{\"lte\":" + endTime + ",\"gt\":" + startTime + "}}}]}") + "&sort=collecTime:asc";
  631. this.goOpenGJ(url)
  632. },
  633. goOpenGJ: function (url) {
  634. var _this = window.gjThis;
  635. window.doXHR(url, function (data) {
  636. if (data && data.resultList && data.resultList.length && data.resultList.length > 0) {
  637. var icon;
  638. if (_this.gjLayer.gjPoyline[data.resultList[0].attributes._targetID]) {
  639. for (let i in _this.gjLayer.gjPoyline[data.resultList[0].attributes._targetID]) {
  640. _this.gjLayer.layerGroup.removeLayer(_this.gjLayer.gjPoyline[data.resultList[0].attributes._targetID][i]);
  641. }
  642. _this.gjLayer.layerGroup.removeLayer(_this.gjLayer.seMarker['s']);
  643. _this.gjLayer.layerGroup.removeLayer(_this.gjLayer.seMarker['e']);
  644. for (var i in _this.gjLayer.gjCircleMarker[data.resultList[0].attributes._targetID]) {
  645. _this.gjLayer.layerGroup.removeLayer(_this.gjLayer.gjCircleMarker[data.resultList[0].attributes._targetID][i]);
  646. }
  647. _this.gjLayer.gjPoyline[data.resultList[0].attributes._targetID] = {};
  648. _this.gjLayer.gjCircleMarker[data.resultList[0].attributes._targetID] = [];
  649. _this.gjLayer.seMarker = {};
  650. }
  651. var lanlats = [], courses = [], speeds = [], collectimes = [];
  652. for (var i in data.resultList) {
  653. collectimes.push(data.resultList[i].time);
  654. courses.push(data.resultList[i].attributes.course);
  655. speeds.push(data.resultList[i].attributes.speeds);
  656. lanlats.push([data.resultList[i].lat, data.resultList[i].lon]);
  657. if (!_this.gjLayer.gjCircleMarker[data.resultList[i].attributes._targetID]) {
  658. _this.gjLayer.gjCircleMarker[data.resultList[i].attributes._targetID] = [];
  659. }
  660. //_this.gjLayer.gjCircleMarker[data.resultList[i].attributes._targetID].push(L.circleMarker([data.resultList[i].lat, data.resultList[i].lon],{radius:2,color:data.resultList[i].pcolor}).addTo(_this.gjLayer.layerGroup));
  661. }
  662. _this.saveGjPlayCtx();
  663. _this.realtimeUpdate();
  664. _this.gjLayer.gjPoyline[data.resultList[0].attributes._targetID] = L.polyline(lanlats, { color: 'red' }).addTo(_this.gjLayer.layerGroup);
  665. var sicon = L.icon({ iconUrl: window.EASYMAP_CONFIG.myUrl + 'map-easy-client/track_start.png', iconSize: [25, 39], iconAnchor: [12, 39] });
  666. var eicon = L.icon({ iconUrl: window.EASYMAP_CONFIG.myUrl + 'map-easy-client/track_end.png', iconSize: [25, 39], iconAnchor: [12, 39] });
  667. var stitle = formatDate(data.resultList[0].time * 1000);
  668. _this.gjLayer.seMarker['s'] = L.marker([data.resultList[0].lat, data.resultList[0].lon], { icon: sicon, title: stitle }).addTo(_this.gjLayer.layerGroup);
  669. //console.log(data.resultList[data.resultList.length-1].attributes.collectime);
  670. var eTitle = formatDate(data.resultList[data.resultList.length - 1].attributes.time * 1000);
  671. _this.gjLayer.seMarker['e'] = L.marker([data.resultList[data.resultList.length - 1].lat, data.resultList[data.resultList.length - 1].lon], { icon: eicon, title: eTitle }).addTo(_this.gjLayer.layerGroup);
  672. window.map.fitBounds(_this.gjLayer.gjPoyline[data.resultList[0].attributes._targetID].getBounds());
  673. var marker1 = L.Marker.movingMarker(lanlats, 10000, {
  674. autostart: true
  675. , course: data.resultList[data.resultList.length - 1].attributes.course
  676. , speed: data.resultList[data.resultList.length - 1].attributes.speed
  677. , courses: courses
  678. , speeds: speeds
  679. , collectimes: collectimes
  680. , iconUrl: data.resultList[0].markerPath+"?sessionToken="+ window.sessionToken
  681. , title: data.resultList[0].name
  682. , showTitle: true
  683. , markerPopup: this.options.markerPopup
  684. }).addTo(window.map);
  685. marker1.on('click', function () {
  686. if (marker1.isRunning()) {
  687. marker1.pause();
  688. } else if (marker1.isEnded()) {
  689. _this.resumeGjPlayCtx(data.resultList[0].attributes._targetID);
  690. window.map.removeLayer(marker1);
  691. marker1.off('click');
  692. } else {
  693. marker1.start();
  694. }
  695. });
  696. /*
  697. var i = 2
  698. while( i < data.resultList.length-1 ){
  699. if(marker1.isEnded()){
  700. marker1.addLatLng([data.resultList[i].lat, data.resultList[i].lon],10000);
  701. marker1.setIcon(new L.AngleIcon({
  702. course:data.resultList[i].attributes.course
  703. ,speed:data.resultList[i].attributes.speed
  704. ,iconUrl: data.resultList[i].markerPath
  705. }));
  706. i++;
  707. }
  708. }
  709. */
  710. } else {
  711. _this.bindPopup('<b>没有轨迹数据!</b>', { closeOnClick: true });
  712. _this.openPopup(window.map.getCenter());
  713. console.log('没有轨迹数据!');
  714. }
  715. });
  716. },
  717. saveGjPlayCtx: function () {
  718. this.gjPaly.isPlay = true;
  719. this.gjPaly.mapCenter = window.map.getCenter();
  720. this.gjPaly.zoom = window.map.getZoom();
  721. },
  722. resumeGjPlayCtx: function (_targetID) {
  723. this.gjPaly.isPlay = false;
  724. window.map.setView(this.gjPaly.mapCenter, this.gjPaly.zoom);
  725. this.gjPaly.mapCenter = null;
  726. this.gjPaly.zoom = null;
  727. this.gjLayer.layerGroup.clearLayers();
  728. delete this.gjLayer.gjPoyline[_targetID];
  729. this.realtimeUpdate();
  730. },
  731. getTileUrl: function (coords) { // (Point, Number) -> String
  732. var url = L.Util.template(this._url, { s: this._getSubdomain(coords) });
  733. //argis版本的要-1
  734. // url += this.getParamString(this.wmtsParams, url) + "&tilematrix=" + (coords.z) + "&tilerow=" + coords.y + "&tilecol=" + coords.x;
  735. url += this.getParamString(this.wmtsParams, url) + "&tilematrix=" + (coords.z) + "&tilerow=" + coords.y + "&tilecol=" + coords.x + "&sessionToken=" + window.sessionToken;
  736. if (this.wmtsParams.hnjhpt_rid) {
  737. var date = new Date();
  738. var time = date.getTime();
  739. var message = this.wmtsParams.hnjhpt_sid + this.wmtsParams.hnjhpt_rid + time;
  740. var hash = CryptoJS.HmacSHA256(message, this.wmtsParams.secret);
  741. var hashInBase64 = CryptoJS.enc.Base64.stringify(hash);
  742. url += "&hnjhpt_sign=" + encodeURIComponent(hashInBase64) + "&hnjhpt_rtime=" + time
  743. }
  744. return url;
  745. },
  746. getJsonTileUrl: function (coords) { // (Point, Number) -> String
  747. var url = L.Util.template(this._jsonUrl, { s: this._getSubdomain(coords) });
  748. var param = L.extend({}, this.wmtsParams);
  749. param.format = "realtime";
  750. url += this.getParamString(param, url) + "&tilematrix=" + (coords.z) + "&tilerow=" + coords.y + "&tilecol=" + coords.x;
  751. if (this.wmtsParams.hnjhpt_rid) {
  752. var date = new Date();
  753. var time = date.getTime();
  754. var message = this.wmtsParams.hnjhpt_sid + this.wmtsParams.hnjhpt_rid + time;
  755. var hash = CryptoJS.HmacSHA256(message, this.wmtsParams.secret);
  756. var hashInBase64 = CryptoJS.enc.Base64.stringify(hash);
  757. url += "&hnjhpt_sign=" + encodeURIComponent(hashInBase64) + "&hnjhpt_rtime=" + time
  758. }
  759. return url;
  760. },
  761. getJsonMarker: function (coords, callback) {
  762. var _this = this;
  763. window.doXHR(this.getJsonTileUrl(coords), function (data) {
  764. if (data && data.resultList && data.resultList.length && data.resultList.length > 0) {
  765. if (callback) {
  766. callback(data.resultList);
  767. }
  768. }
  769. });
  770. },
  771. });
  772. L.tileLayer.wmts.realtime = function (url, jsonUrl, options, markerClick) {
  773. return new L.TileLayer.WMTS.REALTIME(url, jsonUrl, options, markerClick);
  774. };
  775. L.REALTIMEGJ = L.Layer.extend({
  776. options: {
  777. targetIDField: 'attributes._targetID',
  778. timeField: 'attributes.collecTime',
  779. sort: 'collecTime:asc',
  780. playSpeed: 10000,
  781. markerPopup: window.getMarkerPopup,
  782. routeLine: ''
  783. },
  784. url: '',
  785. layername: '',
  786. startTime: null,
  787. endTime: null,
  788. targetList: [],
  789. realtimeIcon: {},
  790. markerGroup: {},
  791. realtimeGJLayer: {},
  792. markerDrawJ: null,
  793. pupopOpenHander: null,
  794. gjLayer: {},
  795. gjPaly: {},
  796. gjData: {},
  797. eventMap: {},
  798. pupopOpenHander: null,
  799. markerDrawJ: null,
  800. initialize: function (url, options) {
  801. this.url = url;
  802. this.gjLayer.layerGroup = L.layerGroup().addTo(window.map);
  803. this.gjLayer.gjCircleMarker = {};
  804. this.gjLayer.gjTimeMarker = {};
  805. this.gjLayer.gjPoyline = {};
  806. this.gjLayer.seMarker = {};
  807. this.gjLayer.movingMarker = {};
  808. L.setOptions(this, options);
  809. },
  810. getGJUrl: function () {
  811. //{\"terms\":{\""+this.options.targetIDField+"\":["+ids.join(',')+"]}},
  812. console.log(this.url + "?format=json&layer=" + this.layername
  813. + "&customsQuery=" + encodeURIComponent("{\"must\":[{\"terms\":{\"" + this.options.targetIDField + "\":[" + this.targetList.join(',') + "]}},{\"range\":{\"" + this.options.timeField + "\":{\"lte\":" + this.endTime + ",\"gt\":" + this.startTime + "}}}]}") + "&sort=" + this.options.sort)
  814. //,{\"range\":{\""+this.options.timeField+"\":{\"lte\":"+this.endTime+",\"gte\":"+this.startTime+"}}}
  815. // return this.url + "?format=json&layer=" + this.layername
  816. // + "&customsQuery=" + encodeURIComponent("{\"must\":[{\"terms\":{\"" + (this.layername.indexOf("zt_clzt") !== -1 ? this.options.CarTargetIDField : this.options.targetIDField) + "\":[" + "\"" + this.targetList.join(',') + "\"" + "]}},{\"range\":{\"" + this.options.timeField + "\":{\"lte\":" + this.endTime + ",\"gt\":" + this.startTime + "}}}]}") + "&sort=" + this.options.sort;
  817. return this.url + "?format=json&layer=" + this.layername
  818. + "&customsQuery=" + encodeURIComponent("{\"must\":[{\"terms\":{\"" + this.options.targetIDField + "\":[" + this.targetList.join(',') + "]}},{\"range\":{\"" + this.options.timeField + "\":{\"lte\":" + this.endTime + ",\"gt\":" + this.startTime + "}}}]}") + "&sort=" + this.options.sort;
  819. },
  820. clearGjLayerLayerGroup: function (_targetID) {
  821. if (this.gjLayer.gjPoyline[_targetID]) {
  822. for (let i in this.gjLayer.gjPoyline[_targetID]) {
  823. this.gjLayer.layerGroup.removeLayer(this.gjLayer.gjPoyline[_targetID][i]);
  824. }
  825. this.gjLayer.layerGroup.removeLayer(this.gjLayer.gjPoyline[_targetID]);
  826. }
  827. if (this.gjLayer.seMarker[_targetID] && this.gjLayer.seMarker[_targetID]['s']) {
  828. this.gjLayer.layerGroup.removeLayer(this.gjLayer.seMarker[_targetID]['s']);
  829. }
  830. if (this.gjLayer.seMarker[_targetID] && this.gjLayer.seMarker[_targetID]['e']) {
  831. this.gjLayer.layerGroup.removeLayer(this.gjLayer.seMarker[_targetID]['e']);
  832. }
  833. for (var i in this.gjLayer.gjCircleMarker[_targetID]) {
  834. this.gjLayer.layerGroup.removeLayer(this.gjLayer.gjCircleMarker[_targetID][i]);
  835. }
  836. for (var i in this.gjLayer.gjTimeMarker[_targetID]) {
  837. this.gjLayer.layerGroup.removeLayer(this.gjLayer.gjTimeMarker[_targetID][i]);
  838. }
  839. let movingMarker = this.gjLayer.movingMarker[_targetID]
  840. if (movingMarker) {
  841. movingMarker.del()
  842. this.gjLayer.layerGroup.removeLayer(movingMarker);
  843. }
  844. // this.gjLayer.layerGroup.clearLayers();
  845. delete this.gjLayer.movingMarker[_targetID]
  846. this.gjLayer.gjPoyline[_targetID] = [];
  847. this.gjLayer.gjCircleMarker[_targetID] = [];
  848. this.gjLayer.gjTimeMarker[_targetID] = [];
  849. this.gjLayer.seMarker[_targetID] = {};
  850. },
  851. stopGuiji: function (targetList) {
  852. targetList.forEach((e) => {
  853. this.clearGjLayerLayerGroup(e);
  854. })
  855. },
  856. pauseGuiji: function (targetList) {
  857. targetList.forEach((e) => {
  858. this.gjLayer.movingMarker[e].pause()
  859. })
  860. },
  861. jixuHuifang: function (targetList) {
  862. targetList.forEach((e) => {
  863. this.gjLayer.movingMarker[e].start()
  864. })
  865. },
  866. followMarker(targetId) {
  867. Object.keys(this.gjLayer.movingMarker).forEach((id) => {
  868. let marker = this.gjLayer.movingMarker[id]
  869. console.log(id, targetId)
  870. if (id === targetId) {
  871. if (marker.isFollow) {
  872. marker.stopFollow()
  873. } else {
  874. marker.follow()
  875. }
  876. } else {
  877. marker.stopFollow()
  878. }
  879. })
  880. // let marker = this.gjLayer.movingMarker[targetId]
  881. // marker.follow()
  882. },
  883. showGJTime: function (show) {
  884. for (let i in this.gjLayer.gjTimeMarker) {
  885. for (let j in this.gjLayer.gjTimeMarker[i]) {
  886. if (!this.gjLayer.layerGroup.hasLayer(this.gjLayer.gjTimeMarker[i][j])) {
  887. if (show) {
  888. this.gjLayer.gjTimeMarker[i][j].addTo(this.gjLayer.layerGroup)
  889. }
  890. } else {
  891. if (!show) {
  892. this.gjLayer.layerGroup.removeLayer(this.gjLayer.gjTimeMarker[i][j]);
  893. }
  894. }
  895. }
  896. }
  897. },
  898. startPlayGJ: function (_targetID, gjData) {
  899. this.clearGjLayerLayerGroup(_targetID);
  900. var lanlats = [], courses = [], speeds = [], collectimes = [];
  901. if (!this.gjLayer.gjCircleMarker[_targetID]) {
  902. this.gjLayer.gjCircleMarker[_targetID] = [];
  903. }
  904. if (!this.gjLayer.seMarker[_targetID]) {
  905. this.gjLayer.seMarker[_targetID] = {};
  906. }
  907. let iconAnchor, noRealtimeGjList = {};
  908. this.gjLayer.gjPoyline[_targetID] = {};
  909. for (var i in gjData) {
  910. collectimes.push(gjData[i].attributes.collecTime);
  911. courses.push(gjData[i].attributes.course);
  912. speeds.push(gjData[i].attributes.speed);
  913. lanlats.push([gjData[i].lat, gjData[i].lon]);
  914. // this.gjLayer.gjCircleMarker[_targetID].push(L.circleMarker([gjData[i].lat, gjData[i].lon],{radius:4,color:'#f00'}).addTo(this.gjLayer.layerGroup));
  915. // this.gjLayer.gjPoyline[_targetID] = L.polyline(lanlats, {color: 'red',dashArray:'10',dashOffset:'2'}).addTo(this.gjLayer.layerGroup);
  916. //处理过虚拟位置不打点
  917. if (gjData[i].attributes.no_realtime_gj
  918. && gjData[i].attributes.no_realtime_gj === 'no_realtime_gj') {
  919. noRealtimeGjList[i] = i;
  920. if (i !== 0 && !(gjData[i].lat + "_" + gjData[i].lon in (this.gjLayer.gjPoyline[_targetID]))) {
  921. this.gjLayer.gjPoyline[_targetID][gjData[i].lat + "_" + gjData[i].lon]
  922. = L.polyline([[gjData[i - 1].lat, gjData[i - 1].lon]
  923. , [gjData[i].lat, gjData[i].lon]], { color: 'red', dashArray: '10' }).addTo(this.gjLayer.layerGroup);
  924. }
  925. continue;
  926. }
  927. if (i !== "0" && !(gjData[i].lat + "_" + gjData[i].lon in (this.gjLayer.gjPoyline[_targetID]))) {
  928. this.gjLayer.gjPoyline[_targetID][gjData[i].lat + "_" + gjData[i].lon]
  929. = L.polyline([[gjData[i - 1].lat, gjData[i - 1].lon]
  930. , [gjData[i].lat, gjData[i].lon]], { color: 'red' }).addTo(this.gjLayer.layerGroup);
  931. }
  932. let m = L.circleMarker([gjData[i].lat, gjData[i].lon], { zIndexOffset: 10, radius: 2, color: '#f00' }).addTo(this.gjLayer.layerGroup);
  933. this.gjLayer.gjCircleMarker[_targetID].push(m);
  934. m.attributes = gjData[i];
  935. m.bindPopup(this.options.markerPopup(m.attributes), { autoPan: false, closeButton: false, offset: L.point(130, 315) }); //autoPanPaddingBottomRight ,,{autoPan:false,closeButton:false,offset:L.point(120,185)}
  936. // var url = _this._jsonUrl+"?format=json&layer="+_this.options.gjLayer+"&customsQuery="+encodeURIComponent("{\"must\":[{\"term\":{\"attributes._targetID\":\""+attr.attributes._targetID+"\"}},{\"range\":{\"attributes.collectime\":{\"lte\":"+endTime+",\"gt\":"+startTime+"}}}]}")+"&sort=collectime:asc";
  937. let _this = this;
  938. m.on('mouseover', function (ev) {
  939. if (_this.pupopOpenHander) {
  940. clearTimeout(_this.pupopOpenHander);
  941. }
  942. _this.pupopOpenHander = setTimeout(function () {
  943. ev.target.openPopup();
  944. }, 500);
  945. if (_this.markerDrawJ) {
  946. _this.gjLayer.layerGroup.removeLayer(_this.markerDrawJ)
  947. }
  948. _this.markerDrawJ = L.marker(ev.target.getLatLng(), { zIndexOffset: 12, icon: new L.AngleIcon({ iconSize: new L.Point(32, 32) }) }).addTo(_this.gjLayer.layerGroup);
  949. _this.markerDrawJ.options.icon.drawJ();
  950. });
  951. iconAnchor = [-70, 10];
  952. let pos = 'right';
  953. if (i % 2 == 0) {
  954. iconAnchor = [120, 10]
  955. pos = 'left';
  956. }
  957. var title = '-'
  958. var len = gjData[i].time.length;
  959. if(len === 13){
  960. title = formatDate(gjData[i].time * 1);
  961. }else if(len === 10){
  962. title = formatDate(gjData[i].time * 1000);
  963. }
  964. // this.gjLayer.gjTimeMarker[_targetID].push(L.marker([gjData[i].lat, gjData[i].lon],{zIndexOffset:-10,icon:L.divIcon({iconSize: [120, 18] ,iconAnchor:iconAnchor,html:'<span>'+formatDate(gjData[i].attributes.collecTime*1000)+'</span>'})}).addTo(this.gjLayer.layerGroup));
  965. this.gjLayer.gjTimeMarker[_targetID][i] = L.marker([gjData[i].lat, gjData[i].lon], { zIndexOffset: -10, icon: L.iconWithLine({ pos: pos, iconSize: [120, 18], iconAnchor: iconAnchor, html: '<span>' + i+':'+title + '</span>' }) });
  966. //).addTo(this.gjLayer.layerGroup));
  967. }
  968. var sicon = L.icon({ iconUrl: window.EASYMAP_CONFIG.myUrl + 'map-easy-client/track_start.png', iconSize: [25, 39], iconAnchor: [12, 39] });
  969. var eicon = L.icon({ iconUrl: window.EASYMAP_CONFIG.myUrl + 'map-easy-client/track_end.png', iconSize: [25, 39], iconAnchor: [12, 39] });
  970. var stitle = formatDate(gjData[0].time * 1000);
  971. this.gjLayer.seMarker[_targetID]['s'] = L.marker([gjData[0].lat, gjData[0].lon], { icon: sicon, title: stitle }).addTo(this.gjLayer.layerGroup);
  972. //console.log(data.resultList[data.resultList.length-1].attributes.collectime);
  973. var eTitle = formatDate(gjData[gjData.length - 1].time * 1000);
  974. this.gjLayer.seMarker[_targetID]['e'] = L.marker([gjData[gjData.length - 1].lat, gjData[gjData.length - 1].lon], { icon: eicon, title: eTitle }).addTo(this.gjLayer.layerGroup);
  975. var marker1 = L.Marker.movingMarker(lanlats, this.options.playSpeed, {
  976. autostart: true
  977. , course: gjData[gjData.length - 1].attributes.course
  978. , speed: gjData[gjData.length - 1].attributes.speed
  979. , courses: courses
  980. , speeds: speeds
  981. , collectimes: collectimes
  982. , iconUrl: gjData[0].markerPath+"?sessionToken="+ window.sessionToken
  983. , zIndexOffset: 100
  984. , title: gjData[gjData.length - 1].name
  985. , showTitle: true
  986. , labelPosition: 'topleft'
  987. , noRealtimeGjList: noRealtimeGjList
  988. , gjTimeMarker: this.gjLayer.gjTimeMarker[_targetID]
  989. , layerGroup: this.gjLayer.layerGroup
  990. , markerDrawJ: this.markerDrawJ
  991. , gjData: gjData
  992. , pupopOpenHander: this.pupopOpenHander
  993. , markerPopup: this.options.markerPopup
  994. }).addTo(this.gjLayer.layerGroup);
  995. /* marker1.on('click', function() {
  996. if (marker1.isRunning()) {
  997. marker1.pause();
  998. } else if(marker1.isEnded()){
  999. //_this.resumeGjPlayCtx(gjData[0].attributes._targetID);
  1000. //window.map.removeLayer(marker1);
  1001. //marker1.off('click');
  1002. } else{
  1003. marker1.start();
  1004. }
  1005. });*/
  1006. this.gjLayer.movingMarker[_targetID] = marker1;
  1007. this.gjLayer.shipOne = marker1
  1008. },
  1009. _playGJ: function () {
  1010. for (var target in this.gjData) {
  1011. let _this = this;
  1012. setTimeout(function (data) {
  1013. _this.startPlayGJ(data.target, data.data)
  1014. }, 100, { target: target, data: this.gjData[target] })
  1015. }
  1016. },
  1017. playGJ: function (layername, targetList, startTime, endTime, noDataPalyCallBack) {
  1018. if (layername) {
  1019. this.layername = layername
  1020. }
  1021. if (targetList && targetList.length > 0) {
  1022. this.targetList = targetList
  1023. }
  1024. if (startTime) {
  1025. this.startTime = startTime
  1026. }
  1027. if (endTime) {
  1028. this.endTime = endTime
  1029. }
  1030. var _this = this;
  1031. window.doXHR(this.getGJUrl(), function (data) {
  1032. //console.log(data)
  1033. if (data && data.resultList && data.resultList.length && data.resultList.length > 0) {
  1034. let obj = {}
  1035. data.resultList.forEach((e) => {
  1036. let id = e.attributes._targetID
  1037. if (id in obj) {
  1038. obj[id].push(e)
  1039. } else {
  1040. obj[id] = [e]
  1041. }
  1042. })
  1043. _this.gjData = obj
  1044. // for( var i in data.resultList ){
  1045. // if( data.resultList[i].attributes._targetID in _this.gjData ){
  1046. // _this.gjData[data.resultList[i].attributes._targetID].push(data.resultList[i]);
  1047. // }else{
  1048. // _this.gjData[data.resultList[i].attributes._targetID] = [];
  1049. // _this.gjData[data.resultList[i].attributes._targetID].push(data.resultList[i]);
  1050. // }
  1051. // }
  1052. _this._playGJ();
  1053. } else {
  1054. if (noDataPalyCallBack) {
  1055. noDataPalyCallBack();
  1056. }
  1057. //window.$message.error('没有轨迹数据!')
  1058. // L.marker(window.map.getCenter()).addTo(_this.gjLayer.layerGroup).bindTooltip('<b>没有轨迹数据!</b>').openTooltip(window.map.getCenter());
  1059. console.log('没有轨迹数据!');
  1060. }
  1061. });
  1062. }
  1063. });
  1064. L.realtimeGj = function (url, layername, targetList, startTime, endTime, options) {
  1065. return new L.REALTIMEGJ(url, layername, targetList, startTime, endTime, options);
  1066. };
  1067. /* Angle ICON */
  1068. L.AngleIcon = L.Icon.extend({
  1069. // default value
  1070. options: {
  1071. angle: 0,
  1072. iconSize: new L.Point(62, 62), // canvas size
  1073. className: "leaflet-boat-icon",
  1074. course: 0, // angle
  1075. labelAnchor: [0, 26], // test loaction
  1076. pointType: 0, // pointType
  1077. showTitle: false,
  1078. label: 'wwwwwwwwwww',
  1079. labelPosition: 'topleft',//topleft , topright , bottomleft,bottomright
  1080. textColor: 'red',
  1081. img: null,
  1082. },
  1083. createIcon: function () {
  1084. var div = document.createElement("div");
  1085. var e = document.createElement("canvas");
  1086. div.appendChild(e);
  1087. var nameDiv = document.createElement("div");
  1088. div.appendChild(nameDiv);
  1089. this._setIconStyles(div, "icon");
  1090. var s = this.options.iconSize;
  1091. e.width = s.x;
  1092. e.height = s.y;
  1093. this.ctx = e.getContext("2d");
  1094. if (this.options.iconUrl) {
  1095. this.draw(s.x, s.y);
  1096. }
  1097. if (this.options.showTitle && this.options.label != '') {
  1098. let style = "opacity: 0.8;position: relative;background-color: #fff;padding-left: 3px;padding-right: 3px;border-radius: 2px;white-space: nowrap;z-index:-3000;";
  1099. if (this.options.labelPosition === 'bottomleft') {
  1100. nameDiv.style = "bottom:15px;left: 52px;float: left;" + style;
  1101. // nameDiv.innerHTML = "<span style='text-align: right;font-size: 10px;font-family: bold ; color: rgb(131 152 138 / 80%);'>"+this.options.label+"</span>";
  1102. } else if (this.options.labelPosition === 'bottomright') {
  1103. nameDiv.style = "bottom:15px;right: 62px;float: right;" + style;
  1104. // nameDiv.innerHTML = "<span style='text-align: right;font-size: 10px;font-family: bold ; color: rgb(131 152 138 / 80%);'>"+this.options.label+"</span>";
  1105. } else if (this.options.labelPosition === 'topleft') {
  1106. nameDiv.style = "top:-70px;left: 62px;float: left;" + style;
  1107. // nameDiv.innerHTML = "<span style='text-align: right;font-size: 10px;font-family: bold ; color: rgb(131 152 138 / 80%);'>"+this.options.label+"</span>";
  1108. } else if (this.options.labelPosition === 'topright') {
  1109. nameDiv.style = "top:-70px;right: 62px;float: right;" + style;
  1110. }
  1111. nameDiv.innerHTML = "<span style='text-align: right;font-size: 10px;font-family: bold ; color: rgb(131 152 138 / 80%);z-index:-3000;'>" + this.options.label + "</span>";
  1112. this.drawLabelLine();
  1113. }
  1114. return div;
  1115. },
  1116. drawLabelLine: function () {
  1117. //画线,指向label
  1118. this.ctx.beginPath();
  1119. let moveTo = [32, 32], lineTo = [52, 52]
  1120. if (this.options.labelPosition === 'bottomleft') {
  1121. moveTo = [32, 32], lineTo = [52, 52]
  1122. } else if (this.options.labelPosition === 'bottomright') {
  1123. moveTo = [32, 32], lineTo = [0, 52]
  1124. } else if (this.options.labelPosition === 'topleft') {
  1125. moveTo = [32, 32], lineTo = [62, 12]
  1126. } else if (this.options.labelPosition === 'topright') {
  1127. moveTo = [32, 32], lineTo = [0, 12]
  1128. }
  1129. this.ctx.moveTo(moveTo[0], moveTo[1]);
  1130. this.ctx.lineTo(lineTo[0], lineTo[1]);
  1131. this.ctx.strokeStyle = '#83988acc';
  1132. this.ctx.lineWidth = "1";
  1133. this.ctx.stroke();
  1134. this.ctx.closePath();
  1135. },
  1136. draw: function (w, h) {
  1137. if (!this.ctx)
  1138. return;
  1139. var course = this.options.course;
  1140. var img = this._createImg(this.options.iconUrl, img);
  1141. var _this = this;
  1142. img.onload = function () {
  1143. //平移坐标原点
  1144. _this.ctx.translate(w / 2, h / 2);
  1145. //旋转画布
  1146. //var course = _this.options.course - 90;
  1147. /*if(course < 0 ){
  1148. course *= -1;
  1149. }
  1150. */
  1151. var rotate = ((Math.PI * 2) / 360) * course;
  1152. /*if(_this.options.course > 180){
  1153. course = -360 + _this.options.course
  1154. }*/
  1155. //console.log(rotate);
  1156. _this.ctx.rotate(rotate);
  1157. _this.ctx.translate(-w / 2, -h / 2);
  1158. //画图
  1159. //_this.ctx.drawImage(img,0,0,32,32); 42/2=21 ,
  1160. _this.ctx.drawImage(img, 18, 18, 26, 26);
  1161. _this.ctx.beginPath();
  1162. _this.ctx.moveTo(31, 18);
  1163. _this.ctx.lineTo(31, 18.0 - (26.0 * _this.options.speed / 10.0));
  1164. //console.log(Math.abs(_this.options.angle));
  1165. if ((_this.options.speed <= 1 && _this.options.course > 0) || Math.abs(_this.options.angle) > 1) {
  1166. _this.ctx.lineTo(38, 18.0 - (26.0 * _this.options.speed / 10.0));
  1167. }
  1168. _this.ctx.strokeStyle = '#000';//'#83988acc';
  1169. _this.ctx.lineJoin = "round";
  1170. _this.ctx.lineWidth = "1";
  1171. _this.ctx.stroke();
  1172. _this.ctx.closePath();
  1173. //console.log(img.src)
  1174. }
  1175. },
  1176. drawJ() {
  1177. var ctx = this.ctx;
  1178. var lefttop = [4, 10], leftbuttom = [4, 24], righttop = [28, 10], rightbuttom = [28, 24];
  1179. var offset = 6;
  1180. //左上角
  1181. ctx.beginPath();
  1182. ctx.moveTo(lefttop[0], lefttop[1]);
  1183. ctx.lineTo(lefttop[0], lefttop[1] - offset);
  1184. ctx.lineTo(lefttop[0] + offset, lefttop[1] - offset);
  1185. ctx.strokeStyle = 'red';
  1186. ctx.lineJoin = "round";
  1187. ctx.lineWidth = "3";
  1188. ctx.stroke();
  1189. ctx.closePath();
  1190. ctx.beginPath();
  1191. ctx.moveTo(lefttop[0], lefttop[1]);
  1192. ctx.lineTo(lefttop[0], lefttop[1] - offset);
  1193. ctx.lineTo(lefttop[0] + offset, lefttop[1] - offset);
  1194. ctx.strokeStyle = '#000';
  1195. ctx.lineJoin = "round";
  1196. ctx.lineWidth = "1";
  1197. ctx.stroke();
  1198. ctx.closePath();
  1199. //左下角 //drawJ(ctx,2,42,2,14,8,14); 46 leftbuttom=[2,40]
  1200. ctx.beginPath();
  1201. ctx.moveTo(leftbuttom[0], leftbuttom[1]);
  1202. ctx.lineTo(leftbuttom[0], leftbuttom[1] + offset);
  1203. ctx.lineTo(leftbuttom[0] + offset, leftbuttom[1] + offset);
  1204. ctx.strokeStyle = 'red';
  1205. ctx.lineJoin = "round";
  1206. ctx.lineWidth = "3";
  1207. ctx.stroke();
  1208. ctx.closePath();
  1209. ctx.beginPath();
  1210. ctx.moveTo(leftbuttom[0], leftbuttom[1]);
  1211. ctx.lineTo(leftbuttom[0], leftbuttom[1] + offset);
  1212. ctx.lineTo(leftbuttom[0] + offset, leftbuttom[1] + offset);
  1213. ctx.strokeStyle = '#000';
  1214. ctx.lineJoin = "round";
  1215. ctx.lineWidth = "1";
  1216. ctx.stroke();
  1217. ctx.closePath();
  1218. //右上角 //drawJ(ctx,2,42,2,14,8,14); 30,24 righttop = [30,20],rightbuttom=[30,40];
  1219. ctx.beginPath();
  1220. ctx.moveTo(righttop[0], righttop[1]);
  1221. ctx.lineTo(righttop[0], righttop[1] - offset);
  1222. ctx.lineTo(righttop[0] - offset, righttop[1] - offset);
  1223. ctx.strokeStyle = 'red';
  1224. ctx.lineJoin = "round";
  1225. ctx.lineWidth = "3";
  1226. ctx.stroke();
  1227. ctx.closePath();
  1228. ctx.beginPath();
  1229. ctx.moveTo(righttop[0], righttop[1]);
  1230. ctx.lineTo(righttop[0], righttop[1] - offset);
  1231. ctx.lineTo(righttop[0] - offset, righttop[1] - offset);
  1232. ctx.strokeStyle = '#000';
  1233. ctx.lineJoin = "round";
  1234. ctx.lineWidth = "1";
  1235. ctx.stroke();
  1236. ctx.closePath();
  1237. //右下角 //drawJ(ctx,2,42,2,14,8,14); 30,24 rightbuttom=[30,40];
  1238. ctx.beginPath();
  1239. ctx.moveTo(rightbuttom[0], rightbuttom[1]);
  1240. ctx.lineTo(rightbuttom[0], rightbuttom[1] + offset);
  1241. ctx.lineTo(rightbuttom[0] - offset, rightbuttom[1] + offset);
  1242. ctx.strokeStyle = 'red';
  1243. ctx.lineJoin = "round";
  1244. ctx.lineWidth = "3";
  1245. ctx.stroke();
  1246. ctx.closePath();
  1247. ctx.beginPath();
  1248. ctx.moveTo(rightbuttom[0], rightbuttom[1]);
  1249. ctx.lineTo(rightbuttom[0], rightbuttom[1] + offset);
  1250. ctx.lineTo(rightbuttom[0] - offset, rightbuttom[1] + offset);
  1251. ctx.strokeStyle = '#000';
  1252. ctx.lineJoin = "round";
  1253. ctx.lineWidth = "1";
  1254. ctx.stroke();
  1255. ctx.closePath();
  1256. },
  1257. /**
  1258. * 获得两点之间方向角 (Get the direction angle between two points)
  1259. * 根据地球上两点之间的经纬度计算两点之间与正北方向的夹角
  1260. * (According to the latitude and longitude between two points on earth,
  1261. * calculate the angle between two points and the direction of the north)
  1262. *
  1263. * @param 点A(L.Latlng) PointA
  1264. * @param 点B(L.Latlng) PointB
  1265. * @return result: AB角度 (the angle of AB (calculated result degree))
  1266. *
  1267. * @version 2016-08-19
  1268. *
  1269. * @see Math.atan2()用于返回从x轴到指定坐标点(x, y)的角度(以弧度为单位);y/x = tan#
  1270. * Math.atan2 () returns the angle (in radians) from the x-axis to the specified coordinate point (x, y); y / x = tan #
  1271. * @version 2016-08-19
  1272. */
  1273. getAngle: function (A, B) {
  1274. var angle = null;
  1275. var latA = A.lat;
  1276. var lonA = A.lng;
  1277. var latB = B.lat;
  1278. var lonB = B.lng;
  1279. // 注意经度或者纬度相等 (when longitude or latitude is equal)
  1280. if (lonA == lonB && latA > latB) {
  1281. angle = Math.PI;
  1282. }
  1283. else if (lonA == lonB && latA < latB) {
  1284. angle = 0;
  1285. }
  1286. else if (lonA > lonB && latA == latB) {
  1287. angle = -(Math.PI / 2);
  1288. }
  1289. else if (lonA < lonB && latA == latB) {
  1290. angle = Math.PI / 2;
  1291. }
  1292. // 注意经度或者纬度都不相等 (Longitude and latitude are not equal)
  1293. else {
  1294. var x1 = latA * Math.pow(10, 12);
  1295. var x2 = latB * Math.pow(10, 12);
  1296. var y1 = lonA * Math.pow(10, 12);
  1297. var y2 = lonB * Math.pow(10, 12);
  1298. angle = Math.atan2(y2 - y1, x2 - x1)
  1299. }
  1300. this.options.angle = angle;
  1301. return angle;
  1302. },
  1303. });
  1304. // AngleMarker继承Marker并添加setHeading 和 getAngle 方法
  1305. // AngleMarker extends from Marker and adds the setHeading and getAngle methods
  1306. L.AngleMarker = L.Marker.extend({
  1307. initialize: function (latlngs, options) {
  1308. options.icon = new L.AngleIcon({
  1309. showTitle: options.showTitle,
  1310. label: options.title,
  1311. labelPosition: options.labelPosition,
  1312. textColor: options.labelColor,
  1313. img: options.img,
  1314. course: options.course,
  1315. speed: options.speed,
  1316. angle: options.angle,
  1317. iconUrl: options.iconUrl
  1318. })
  1319. L.Marker.prototype.initialize.call(this, latlngs, options);
  1320. },
  1321. getAngle: function (A, B) {
  1322. return this.options.icon.getAngle(A, B);
  1323. },
  1324. setHeading: function (heading) {
  1325. this.options.icon.setHeading(heading);
  1326. },
  1327. updatePosAndIcon: function (newLanlng, attributes, icon) {
  1328. if (this._icon) {
  1329. L.DomUtil.remove(this._icon);
  1330. }
  1331. //layerGroup.removeLayer(this);
  1332. var angle = '';
  1333. if (newLanlng) {
  1334. angle = this.options.angle = this.getAngle(this.getLatLng(), newLanlng);
  1335. //console.log(this.options.angle);
  1336. this.setLatLng(newLanlng);
  1337. }
  1338. if (!icon) {
  1339. this.setIcon(new L.AngleIcon({
  1340. course: attributes.attributes.course,
  1341. speed: attributes.attributes.speed,
  1342. iconUrl: this.options.iconUrl,
  1343. angle: angle,
  1344. label: attributes.name,
  1345. showTitle: this.showTitle,
  1346. labelPosition: this.options.labelPosition
  1347. }));
  1348. } else {
  1349. this.setIcon(icon);
  1350. }
  1351. //layerGroup.addLayer(this);
  1352. }
  1353. });
  1354. L.angleMarker = function (pos, options) {
  1355. return new L.AngleMarker(pos, options);
  1356. };
  1357. L.iconWithLine = function (options) {
  1358. return new L.IconWithLine(options);
  1359. };
  1360. L.IconWithLine = L.Icon.extend({
  1361. options: {
  1362. html: '',
  1363. pos: 'left'
  1364. },
  1365. createIcon: function () {
  1366. var div = document.createElement("div");
  1367. var e = document.createElement("canvas");
  1368. var timeDiv = document.createElement("div");
  1369. div.appendChild(e);
  1370. div.appendChild(timeDiv);
  1371. let estyle = "left:-7px;top:9px;float:right;position: relative;";
  1372. let timeDivstyle = "float:left;left: -29px;opacity: 0.8;position: relative;background-color: #fff;padding-left: 3px;padding-right: 3px;border-radius: 2px;white-space: nowrap;z-index:-3000;";
  1373. e.width = 25;
  1374. e.height = 4;
  1375. if (this.options.pos === 'right') {
  1376. estyle = "left:-62px;top:9px;float:left;position: relative;";
  1377. timeDivstyle = "float:right;left: -37px;opacity: 0.8;position: relative;background-color: #fff;padding-left: 3px;padding-right: 3px;border-radius: 2px;white-space: nowrap;z-index:-3000;";
  1378. e.width = 25;
  1379. e.height = 4;
  1380. } else if (this.options.pos === 'top') {
  1381. estyle = "left:-71px;top:17px;float:left;position: relative;";
  1382. timeDivstyle = "float:right;top:17px;left: -75px;opacity: 0.8;position: relative;background-color: #fff;padding-left: 3px;padding-right: 3px;border-radius: 2px;white-space: nowrap;z-index:-3000;";
  1383. e.width = 4;
  1384. e.height = 25;
  1385. } else if (this.options.pos === 'bottom') {
  1386. estyle = "left:-62px;top:9px;float:left;position: relative;";
  1387. timeDivstyle = "float:right;left: -37px;opacity: 0.8;position: relative;background-color: #fff;padding-left: 3px;padding-right: 3px;border-radius: 2px;white-space: nowrap;z-index:-3000;";
  1388. e.width = 4;
  1389. e.height = 25;
  1390. }
  1391. timeDiv.style = timeDivstyle;
  1392. e.style = estyle;
  1393. timeDiv.innerHTML = this.options.html
  1394. this._setIconStyles(div, "icon");
  1395. this.ctx = e.getContext("2d");
  1396. this.drawLabelLine(this.options.pos);
  1397. return div;
  1398. },
  1399. drawLabelLine: function (pos) {
  1400. //画线,指向label
  1401. this.ctx.beginPath();
  1402. if (pos === 'right' || pos === 'left') {
  1403. this.ctx.moveTo(0, 2);
  1404. this.ctx.lineTo(25, 2);
  1405. } else {
  1406. this.ctx.moveTo(2, 0);
  1407. this.ctx.lineTo(2, 25);
  1408. }
  1409. this.ctx.strokeStyle = '#83988acc';
  1410. this.ctx.lineWidth = "0.5";
  1411. this.ctx.stroke();
  1412. this.ctx.closePath();
  1413. },
  1414. });
  1415. Date.prototype.Format = function (fmt) { //author: meizz
  1416. if (!fmt) {
  1417. fmt = 'yyyy-MM-dd hh:mm:ss';
  1418. }
  1419. var o = {
  1420. "M+": this.getMonth() + 1, //月份
  1421. "d+": this.getDate(), //日
  1422. "h+": this.getHours(), //小时
  1423. //"h+": this.getHours()%12 == 0 ? 12 : this.getHours()%12, //小时
  1424. "m+": this.getMinutes(), //分
  1425. "s+": this.getSeconds(), //秒
  1426. "q+": Math.floor((this.getMonth() + 3) / 3), //季度
  1427. "S": this.getMilliseconds() //毫秒
  1428. };
  1429. if (/(y+)/.test(fmt)) fmt = fmt.replace(RegExp.$1, (this.getFullYear() + "").substr(4 - RegExp.$1.length));
  1430. for (var k in o)
  1431. if (new RegExp("(" + k + ")").test(fmt)) fmt = fmt.replace(RegExp.$1, (RegExp.$1.length == 1) ? (o[k]) : (("00" + o[k]).substr(("" + o[k]).length)));
  1432. return fmt;
  1433. }
  1434. window.formatDate = function (time, format) {
  1435. if (!time) {
  1436. return '';
  1437. }
  1438. return new Date(time).Format(format);
  1439. }
  1440. window.doXHR = function (url, callback) {
  1441. var httpXml = window.createXMLHttpRequest();
  1442. httpXml.open('get', url, true);
  1443. httpXml.setRequestHeader("sessionToken",window.sessionToken)
  1444. httpXml.send(null);
  1445. httpXml.onreadystatechange = function () {
  1446. if (httpXml.readyState == 4 && httpXml.status == 200) {
  1447. var data = JSON.parse(httpXml.responseText);
  1448. if (callback) {
  1449. callback(data);
  1450. }
  1451. }
  1452. };
  1453. }
  1454. window.createXMLHttpRequest = function () {
  1455. var xmlHttp;
  1456. try {
  1457. xmlHttp = new XMLHttpRequest();
  1458. } catch (e) {
  1459. // 适用于IE6
  1460. try {
  1461. xmlHttp = new ActiveXObject("Msxml2.XMLHTTP");
  1462. } catch (e) {
  1463. // 适用于IE5.5,以及IE更早版本
  1464. try {
  1465. xmlHttp = new ActiveXObject("Microsoft.XMLHTTP");
  1466. } catch (e) { }
  1467. }
  1468. }
  1469. return xmlHttp;
  1470. }
  1471. window.createWebSocket = function (handle) {
  1472. //第一次连接,创建websocket连接
  1473. // messageType:"websocket",
  1474. // realtimeWebsocket:null,
  1475. //判断当前浏览器是否支持WebSocket
  1476. if (!window.realtimeWebsocket && ('WebSocket' in window)) {
  1477. //经过nginx代理转发websocket,需要对参数进行两次解码,否则无法通过nginx
  1478. window.realtimeWebsocket = new WebSocket(handle.options.websocketUrl + encodeURIComponent(encodeURIComponent(JSON.stringify(handle.getParam()))));
  1479. if (!window.realtimeWebsocketHandle) {
  1480. window.realtimeWebsocketHandle = {};
  1481. }
  1482. //连接成功建立的回调方法
  1483. window.realtimeWebsocket.onopen = function () {
  1484. window.realtimeWebsocketCreated = true;
  1485. window.realtimeWebsocketCreatedOnerror = false;
  1486. handle.messageType = 'websocket';
  1487. console.log("WebSocket连接成功");
  1488. }
  1489. //连接发生错误的回调方法
  1490. window.realtimeWebsocket.onerror = function () {
  1491. window.realtimeWebsocket = null;
  1492. window.realtimeWebsocketCreated = null;
  1493. window.realtimeWebsocketCreatedOnerror = true;
  1494. handle.messageType = 'http';
  1495. console.log("WebSocket连接发生错误");
  1496. };
  1497. //接收到消息的回调方法
  1498. window.realtimeWebsocket.onmessage = function (event) {
  1499. let handle;
  1500. for (let layername in window.realtimeWebsocketHandle) {
  1501. handle = window.realtimeWebsocketHandle[layername];
  1502. if (handle && event && event.data) {
  1503. let data = JSON.parse(event.data);
  1504. if (data && data.layername === layername) {
  1505. handle.realtimeMessageCallback(data, handle);
  1506. }
  1507. }
  1508. }
  1509. }
  1510. //连接关闭的回调方法
  1511. window.realtimeWebsocket.onclose = function () {
  1512. window.realtimeWebsocket = null;
  1513. window.realtimeWebsocketHandle = null;
  1514. window.realtimeWebsocketCreated = null;
  1515. console.log("WebSocket连接关闭");
  1516. }
  1517. //监听窗口关闭事件,当窗口关闭时,主动去关闭websocket连接,防止连接还没断开就关闭窗口,server端会抛异常。
  1518. window.onbeforeunload = function () {
  1519. window.realtimeWebsocket.close();
  1520. }
  1521. }
  1522. if (window.realtimeWebsocket == null) {
  1523. handle.messageType = "http";
  1524. return null;
  1525. }
  1526. if (!window.realtimeWebsocketHandle[handle.options.realtimeLayer]) {
  1527. handle.messageType = "websocket";
  1528. window.realtimeWebsocketHandle[handle.options.realtimeLayer] = handle;
  1529. }
  1530. return window.realtimeWebsocket;
  1531. }