25개 이상의 토픽을 선택하실 수 없습니다. Topics must start with a letter or number, can include dashes ('-') and can be up to 35 characters long.

CarTrack.js 14KB

7 달 전
123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484
  1. /****
  2. * 依赖于天地图的D3.js支持库,以SVG的形式对车辆行驶位置及轨迹进行实时跟踪和动态展示。
  3. * 实现车辆沿路线运动,并有暂停等功能。
  4. * 注:chrome、safari、IE9及以上浏览器。
  5. * @author juyang
  6. * ****/
  7. /**
  8. * 车辆的图片,包含坐标和旋转相关方法
  9. */
  10. var CarOverlay = T.Overlay.extend({
  11. initialize: function (lnglat, options) {
  12. this.lnglat = lnglat;
  13. this.setOptions(options);
  14. this.options = options;
  15. },
  16. onAdd: function (map) {
  17. this.map = map;
  18. var div = this.div = document.createElement("div");
  19. var img = this.img = document.createElement("img");
  20. div.style.position = "absolute";
  21. div.style.width = this.options.width + "px";
  22. div.style.height = this.options.height + "px";
  23. div.style.marginLeft = -this.options.width / 2 + 'px';
  24. div.style.marginTop = -this.options.height / 2 + 'px';
  25. div.style.zIndex = 200;// this._container.style.zIndex = zIndex;
  26. img.style.width = this.options.width + "px";
  27. img.style.height = this.options.height + "px";
  28. img.src = this.options.iconUrl;
  29. div.appendChild(img);
  30. map.getPanes().overlayPane.appendChild(this.div);
  31. this.update(this.lnglat);
  32. },
  33. onRemove: function () {
  34. var parent = this.div.parentNode;
  35. if (parent) {
  36. parent.removeChild(this.div);
  37. this.map = null;
  38. this.div = null;
  39. }
  40. },
  41. /**
  42. * 每个浏览器的偏转兼容
  43. * @returns {string}
  44. * @constructor
  45. */
  46. CSS_TRANSFORM: function () {
  47. var div = document.createElement('div');
  48. var props = [
  49. 'transform',
  50. 'WebkitTransform',
  51. 'MozTransform',
  52. 'OTransform',
  53. 'msTransform'
  54. ];
  55. for (var i = 0; i < props.length; i++) {
  56. var prop = props[i];
  57. if (div.style[prop] !== undefined) {
  58. return prop;
  59. }
  60. }
  61. return props[0];
  62. },
  63. /**
  64. * 偏转角度
  65. * @param rotate
  66. */
  67. setRotate: function (rotate) {
  68. this.img.style[this.CSS_TRANSFORM()] = "rotate(" +
  69. rotate + "deg)";
  70. },
  71. setLnglat: function (lnglat) {
  72. this.lnglat = lnglat;
  73. this.update();
  74. },
  75. getLnglat: function () {
  76. return this.lnglat;
  77. },
  78. setPos: function (pos) {
  79. this.lnglat = this.map.layerPointToLngLat(pos)
  80. this.update();
  81. },
  82. /**
  83. * 更新位置
  84. */
  85. update: function () {
  86. var pos = this.map.lngLatToLayerPoint(this.lnglat);
  87. this.div.style.left = pos.x + "px";
  88. this.div.style.top = pos.y + "px";
  89. }
  90. })
  91. T.CarTrack = function (map, opt) {
  92. this.map = map;
  93. // this.options = opt ? opt : {};
  94. // this.options= this.setOptions(this.options,opt)
  95. //this.options.interval = this.options.interval ? this.options.interval : 1000;
  96. // this.options.uid = new Date().getTime();
  97. // this.uid = this.options.uid
  98. this.options.polylinestyle = this.setOptions(this.options.polylinestyle, opt.polylinestyle)
  99. this.options.carstyle = this.setOptions(this.options.carstyle, opt.carstyle)
  100. this.options = this.setOptions(this.options, opt)
  101. this.init();
  102. }
  103. T.CarTrack.prototype = {
  104. options: {
  105. interval: 1000,
  106. carstyle: {
  107. display: true,
  108. iconUrl: "http://lbs.tianditu.gov.cn/images/openlibrary/car.png",
  109. width: 52,
  110. height: 26
  111. },
  112. polylinestyle: {
  113. display: true,
  114. color: "red",
  115. width: "3",
  116. opacity: 0.8,
  117. lineStyle: ""
  118. }
  119. },
  120. init: function () {
  121. var datas = this.options.Datas;
  122. this.options = this._deepCopy(this.options);
  123. this.options.uid=new Date().getTime();
  124. this.options.Datas = datas;
  125. if (this.options.speed > 0) {
  126. var dis = this.distance(this.options.Datas);
  127. this.options.nodeslength = dis / this.options.speed;//总步数;
  128. }
  129. else {
  130. this.options.nodeslength = this.options.Datas.length;//总步数;
  131. }
  132. //计步器
  133. this.options.Counter = 0;
  134. //new出D3的图层,等待数据
  135. this.D3OverLayer = new T.D3Overlay(this.d3init, this.d3redraw, this.options);
  136. this.D3OverLayer.lineDatas = [];//线数据
  137. //共享两个函数
  138. this.D3OverLayer.dataToLnglat = this.dataToLnglat;
  139. this.D3OverLayer.applyLatLngToLayer = this.applyLatLngToLayer;
  140. //this.D3OverLayer.updateSymbolLine = this.updateSymbolLine;
  141. //接收,处理数据,加载轨迹和车辆;
  142. this.receiveData(this.map);
  143. },
  144. setOptions: function (obj, options) {
  145. for (var i in options) {
  146. if (i != "polylinestyle" && i != "carstyle")
  147. obj[i] = options[i];
  148. }
  149. return obj;
  150. },
  151. /**
  152. * 清除所有元素,注销事件
  153. */
  154. clear: function () {
  155. this.state = 4;
  156. this._Remove();
  157. delete this;
  158. },
  159. _Remove: function () {
  160. this._pause();
  161. delete this._timer;
  162. this._timer = null;
  163. this.map.removeOverLay(this.carMarker);
  164. this.map.removeOverLay(this.D3OverLayer);
  165. },
  166. /**处理传入的数据**/
  167. receiveData: function () {
  168. var opt = this.options;
  169. var me = this;
  170. if (opt.Datas instanceof Array && opt.Datas.length > 0) {
  171. //绘制出D3渲染的线段;
  172. me.map.addOverLay(me.D3OverLayer)
  173. //绘制车辆
  174. me.carMarker = new CarOverlay(me.dataToLnglat(this.options.Datas[0]), me.options.carstyle);
  175. if (!this.options.carstyle)
  176. me.carMarker.hide();
  177. me.map.addOverLay(this.carMarker);
  178. me.D3OverLayer.bringToBack();
  179. }
  180. },
  181. /**
  182. * 坐标获取
  183. * @param obj
  184. * @returns {T.LngLat}
  185. */
  186. dataToLnglat: function (obj) {
  187. if (obj instanceof T.LngLat || ('lat' in obj && 'lng' in obj))
  188. return obj;
  189. else {
  190. var coordinates = obj.geometry.coordinates;
  191. var lnlat = new T.LngLat(coordinates[0], coordinates[1]);
  192. return lnlat;
  193. }
  194. },
  195. bind: function (fn, obj) {
  196. var slice = Array.prototype.slice;
  197. if (fn.bind) {
  198. return fn.bind.apply(fn, slice.call(arguments, 1));
  199. }
  200. },
  201. /**
  202. * 坐标转换
  203. * @param d
  204. * @returns {*}
  205. */
  206. applyLatLngToLayer: function (d) {
  207. return this.map.lngLatToLayerPoint(this.dataToLnglat(d));
  208. },
  209. d3init: function (sel, transform) {
  210. sel.append("path")
  211. .attr("id", "polyline" + this.options.uid)
  212. .attr("fill", "none")
  213. .attr("stroke", this.options.polylinestyle.color)
  214. .attr("width", this.options.polylinestyle.width)
  215. .attr('opacity', this.options.polylinestyle.opacity)
  216. .attr('display', this.options.polylinestyle.display ? "block" : "none")
  217. sel.append("path")
  218. .attr("id", "dynamicLine" + this.options.uid)
  219. .attr("fill", "none")
  220. .attr("stroke", this.options.polylinestyle.color)
  221. .attr("width", this.options.polylinestyle.width)
  222. .attr('opacity', this.options.polylinestyle.opacity)
  223. .attr('display', this.options.dynamicLine && this.options.polylinestyle.display ? "block" : "none")
  224. },
  225. d3redraw: function () {
  226. //像素点坐标转字符串
  227. function pointsToPath(rings, closed) {
  228. var str = '',
  229. i, j, len, len2, points, p;
  230. for (i = 0, len = rings.length; i < len; i++) {
  231. points = rings[i];
  232. for (j = 0, len2 = points.length; j < len2; j++) {
  233. p = points[j];
  234. str += (j ? 'L' : 'M') + p.x + ' ' + p.y;
  235. }
  236. // closes the ring for polygons; "x" is VML syntax
  237. str += closed ? (L.Browser.svg ? 'z' : 'x') : '';
  238. }
  239. // SVG complains about empty path strings
  240. return str || 'M0 0';
  241. }
  242. function lnglatsTopoints(map, lnglats) {
  243. var pts = [];
  244. for (var k = 0; k < lnglats.length; k++) {
  245. pts.push(map.lngLatToLayerPoint(lnglats[k]))
  246. }
  247. return pts;
  248. }
  249. var datasStr1 = pointsToPath([lnglatsTopoints(this.map, this.options.Datas)], false);//this._svg.
  250. var lineDatas = this.lineDatas ? this.lineDatas : this.D3OverLayer.lineDatas;
  251. var datasStr2 = pointsToPath([lnglatsTopoints(this.map, lineDatas)], false);//this.options.dynamicLine ? this.lineDatas : this.options.Datas;
  252. //线数据的重新计算分两种情况 1、缩放地图时要重新计算容器坐标 2、动态线的时候要重绘线
  253. d3.select("path#polyline" + this.options.uid).attr("d", datasStr1)
  254. .attr("stroke-width", this.options.polylinestyle.width + "px");
  255. d3.select("path#dynamicLine" + this.options.uid).attr("d", datasStr2)
  256. .attr("stroke-width", this.options.polylinestyle.width + "px");
  257. },
  258. /**
  259. * 随着时间
  260. */
  261. update: function () {
  262. //计步器+1
  263. this.options.Counter++
  264. var linePath = d3.select('path#polyline' + this.options.uid)
  265. .attr('display', this.options.polylinestyle.display && !this.options.dynamicLine ?
  266. "block" : "none")
  267. //轨迹像素长度
  268. var nodeslength = (this.options.speed > 0 ?
  269. Math.ceil(this.options.nodeslength) + 1 :
  270. Math.ceil(this.options.nodeslength)
  271. )
  272. if (this.options.speed > 0) {
  273. //计算小车所在的像素点
  274. var l = linePath.node().getTotalLength();
  275. var s = (this.options.Counter - 1 ) / this.options.nodeslength
  276. var l1 = s * l;
  277. var p1 = linePath.node().getPointAtLength(l1);
  278. this.D3OverLayer.lineDatas = [];
  279. if (this.options.Datas[0])
  280. this.D3OverLayer.lineDatas.push(this.options.Datas[0]);
  281. var lsum = 0;
  282. // 计算像素点前的所有包含的轨迹坐标的像素点
  283. for (var k = 0; k < this.options.Datas.length - 1; k++) {
  284. var p2 = this.map.lngLatToLayerPoint(this.options.Datas[k]);
  285. var p3 = this.map.lngLatToLayerPoint(this.options.Datas[k + 1]);
  286. var l2 = p2.distanceTo(p3);
  287. lsum = lsum + l2;
  288. if (l1 > lsum)
  289. this.D3OverLayer.lineDatas.push(this.options.Datas[k + 1]);
  290. else {
  291. break;
  292. }
  293. }
  294. if (this.options.Counter < nodeslength) {
  295. var lnglat = this.map.layerPointToLngLat(p1)
  296. this.D3OverLayer.lineDatas.push(lnglat);
  297. }
  298. }
  299. else {
  300. this.D3OverLayer.lineDatas = this.options.Datas.slice(0, this.options.Counter);
  301. }
  302. this.carMarker.setLnglat(this.D3OverLayer.lineDatas[this.D3OverLayer.lineDatas.length - 1]);
  303. //车辆偏转角计算。
  304. if (this.options.Counter > 1) {
  305. var rotate = this.angle(
  306. this.D3OverLayer.lineDatas[this.D3OverLayer.lineDatas.length - 2],
  307. this.D3OverLayer.lineDatas[this.D3OverLayer.lineDatas.length - 1]);
  308. this.carMarker.setRotate(rotate)
  309. }
  310. else {
  311. this.carMarker.setRotate(0)
  312. }
  313. if (this.options.dynamicLine) this.d3redraw();
  314. /**回调函数,车辆每移动一次触发的函数
  315. *Lnglat:经过的坐标
  316. *index:节点序号。
  317. *length:总节点数量。
  318. ***/
  319. if (this.options.passOneNode) this.options.passOneNode(
  320. this.carMarker.getLnglat(),
  321. this.options.Counter,
  322. nodeslength
  323. )
  324. if (this.options.Counter >= nodeslength) {
  325. this.options.Counter = 0;
  326. }
  327. },
  328. /**
  329. * 计算轨迹的距离
  330. * @returns {number}
  331. */
  332. distance: function () {
  333. var d = 0;
  334. var datas = this.options.Datas;
  335. var l = datas.length;
  336. for (var i = 0; i < l - 1; i++) {
  337. var p1 = this.dataToLnglat(datas[i]);
  338. var p2 = this.dataToLnglat(datas[i + 1]);
  339. d = d + this.map.getDistance(p1, p2);
  340. }
  341. return d;
  342. },
  343. /**
  344. *在每个点的真实步骤中设置小车转动的角度
  345. */
  346. angle: function (curPos, targetPos) {
  347. var deg = 0;
  348. if (targetPos.lng != curPos.lng) {
  349. var tan = (targetPos.lat - curPos.lat) / (targetPos.lng - curPos.lng),
  350. atan = Math.atan(tan);
  351. deg = -atan * 360 / (2 * Math.PI);
  352. if (targetPos.lng < curPos.lng) {
  353. deg = -deg + 90 + 90;
  354. } else {
  355. deg = -deg;
  356. }
  357. return -deg;
  358. } else {
  359. var disy = targetPos.lat - curPos.lat;
  360. var bias = 0;
  361. if (disy > 0)
  362. bias = -1
  363. else
  364. bias = 1
  365. return (-bias * 90);
  366. }
  367. return;
  368. },
  369. /**
  370. *开始运动
  371. */
  372. start: function () {
  373. if (this.state == 4)return;
  374. this.state = 1;
  375. if (this.D3OverLayer && !this._timer) {
  376. this._timer = setInterval(this.bind(this.update, this),
  377. this.options.interval);
  378. }
  379. },
  380. /**
  381. * 停止运动
  382. */
  383. stop: function () {
  384. if (this.state == 4)return;
  385. this.state = 2;
  386. this._pause();
  387. this._Remove();
  388. this.init();
  389. },
  390. _pause: function () {
  391. if (this._timer) {
  392. clearTimeout(this._timer);
  393. delete this._timer;
  394. this._timer = null;
  395. }
  396. return this;
  397. },
  398. /**
  399. * 暂停运动
  400. */
  401. pause: function () {
  402. if (this.state == 4)return;
  403. this.state = 3;
  404. this._pause();
  405. },
  406. _deepCopy: function (source) {
  407. var result = {};
  408. for (var key in source) {
  409. result[key] = typeof source[key] === 'object' ? this._deepCopy(source[key]) : source[key];
  410. }
  411. return result;
  412. }
  413. }