Newer
Older
KaiFengH5 / public / static / libs / mapbox / extend / XYZLayer.js
@zhangdeliang zhangdeliang on 24 May 93 KB 项目初始化
  1. (function (global, factory) {
  2. typeof exports === 'object' && typeof module !== 'undefined' ?
  3. module.exports = factory() :
  4. typeof define === 'function' && define.amd ? define(factory) :
  5. (global = typeof globalThis !== 'undefined' ? globalThis :
  6. global || self, global.mapboxgl1.XYZLayer = factory());
  7. }(window, (function () {
  8. 'use strict';
  9.  
  10. /*
  11. * @namespace Util
  12. *
  13. * Various utility functions, used by Leaflet internally.
  14. */
  15. Object.freeze = function (obj) {
  16. return obj;
  17. };
  18.  
  19. // @function create(proto: Object, properties?: Object): Object
  20. // Compatibility polyfill for [Object.create](https://developer.mozilla.org/docs/Web/JavaScript/Reference/Global_Objects/Object/create)
  21. var create$3 = Object.create || function () {
  22. function F() {}
  23. return function (proto) {
  24. F.prototype = proto;
  25. return new F();
  26. };
  27. }();
  28.  
  29. // @function setOptions(obj: Object, options: Object): Object
  30. // Merges the given properties to the `options` of the `obj` object, returning the resulting options. See `Class options`. Has an `L.setOptions` shortcut.
  31. function setOptions(obj, options) {
  32. if (!obj.hasOwnProperty('options')) {
  33. obj.options = obj.options ? create$3(obj.options) : {};
  34. }
  35. for (var i in options) {
  36. obj.options[i] = options[i] || obj.options[i];
  37. }
  38. return obj.options;
  39. }
  40.  
  41. var templateRe = /\{ *([\w_-]+) *\}/g;
  42.  
  43. // @function template(str: String, data: Object): String
  44. // Simple templating facility, accepts a template string of the form `'Hello {a}, {b}'`
  45. // and a data object like `{a: 'foo', b: 'bar'}`, returns evaluated string
  46. // `('Hello foo, bar')`. You can also specify functions instead of strings for
  47. // data values — they will be evaluated passing `data` as an argument.
  48. function template(str, data) {
  49. return str.replace(templateRe, function (str, key) {
  50. var value = data[key];
  51.  
  52. if (value === undefined) {
  53. throw new Error('No value provided for variable ' + str);
  54. } else if (typeof value === 'function') {
  55. value = value(data);
  56. }
  57. return value;
  58. });
  59. }
  60.  
  61. // @function isArray(obj): Boolean
  62. // Compatibility polyfill for [Array.isArray](https://developer.mozilla.org/docs/Web/JavaScript/Reference/Global_Objects/Array/isArray)
  63. var isArray = Array.isArray || function (obj) {
  64. return Object.prototype.toString.call(obj) === '[object Array]';
  65. };
  66.  
  67. //坐标转换
  68. var pi = 3.1415926535897932384626;
  69. var a = 6378245.0;
  70. var ee = 0.00669342162296594323;
  71. var x_pi = pi * 3000.0 / 180.0;
  72.  
  73. /**百度转84*/
  74. function bd09_To_gps84(lng, lat) {
  75. if (isArray(lng)) {
  76. var _lng = lng[0];
  77. lat = lng[1];
  78. lng = _lng;
  79. }
  80. if (lng instanceof Object) {
  81. var _lng = lng.lng;
  82. lat = lng.lat;
  83. lng = _lng;
  84. }
  85. var gcj02 = bd09_To_gcj02(lng, lat);
  86. var map84 = gcj02_To_gps84(gcj02.lng, gcj02.lat);
  87. return map84;
  88. }
  89. /**84转百度*/
  90. function gps84_To_bd09(lng, lat) {
  91. if (isArray(lng)) {
  92. var _lng = lng[0];
  93. lat = lng[1];
  94. lng = _lng;
  95. }
  96. if (lng instanceof Object) {
  97. var _lng = lng.lng;
  98. lat = lng.lat;
  99. lng = _lng;
  100. }
  101. var gcj02 = gps84_To_gcj02(lng, lat);
  102. var bd09 = gcj02_To_bd09(gcj02.lng, gcj02.lat);
  103. return bd09;
  104. }
  105. /**84转火星*/
  106. function gps84_To_gcj02(lng, lat) {
  107. if (isArray(lng)) {
  108. var _lng = lng[0];
  109. lat = lng[1];
  110. lng = _lng;
  111. }
  112. if (lng instanceof Object) {
  113. var _lng = lng.lng;
  114. lat = lng.lat;
  115. lng = _lng;
  116. }
  117.  
  118. var dLat = transformLat(lng - 105.0, lat - 35.0);
  119. var dLng = transformLng(lng - 105.0, lat - 35.0);
  120. var radLat = lat / 180.0 * pi;
  121. var magic = Math.sin(radLat);
  122. magic = 1 - ee * magic * magic;
  123. var sqrtMagic = Math.sqrt(magic);
  124. dLat = dLat * 180.0 / (a * (1 - ee) / (magic * sqrtMagic) * pi);
  125. dLng = dLng * 180.0 / (a / sqrtMagic * Math.cos(radLat) * pi);
  126. var mgLat = lat + dLat;
  127. var mgLng = lng + dLng;
  128. var newCoord = {
  129. lng: mgLng,
  130. lat: mgLat
  131. };
  132. return newCoord;
  133. }
  134. /**火星转84*/
  135. function gcj02_To_gps84(lng, lat) {
  136. if (isArray(lng)) {
  137. var _lng = lng[0];
  138. lat = lng[1];
  139. lng = _lng;
  140. }
  141. if (lng instanceof Object) {
  142. var _lng = lng.lng;
  143. lat = lng.lat;
  144. lng = _lng;
  145. }
  146.  
  147. var coord = transform(lng, lat);
  148. var lontitude = lng * 2 - coord.lng;
  149. var latitude = lat * 2 - coord.lat;
  150. var newCoord = {
  151. lng: lontitude,
  152. lat: latitude
  153. };
  154. return newCoord;
  155. }
  156. /**火星转百度*/
  157. function gcj02_To_bd09(x, y) {
  158. var z = Math.sqrt(x * x + y * y) + 0.00002 * Math.sin(y * x_pi);
  159. var theta = Math.atan2(y, x) + 0.000003 * Math.cos(x * x_pi);
  160. var bd_lng = z * Math.cos(theta) + 0.0065;
  161. var bd_lat = z * Math.sin(theta) + 0.006;
  162. var newCoord = {
  163. lng: bd_lng,
  164. lat: bd_lat
  165. };
  166. return newCoord;
  167. }
  168. /**百度转火星*/
  169. function bd09_To_gcj02(bd_lng, bd_lat) {
  170. var x = bd_lng - 0.0065;
  171. var y = bd_lat - 0.006;
  172. var z = Math.sqrt(x * x + y * y) - 0.00002 * Math.sin(y * x_pi);
  173. var theta = Math.atan2(y, x) - 0.000003 * Math.cos(x * x_pi);
  174. var gg_lng = z * Math.cos(theta);
  175. var gg_lat = z * Math.sin(theta);
  176. var newCoord = {
  177. lng: gg_lng,
  178. lat: gg_lat
  179. };
  180. return newCoord;
  181. }
  182.  
  183. function transform(lng, lat) {
  184. var dLat = transformLat(lng - 105.0, lat - 35.0);
  185. var dLng = transformLng(lng - 105.0, lat - 35.0);
  186. var radLat = lat / 180.0 * pi;
  187. var magic = Math.sin(radLat);
  188. magic = 1 - ee * magic * magic;
  189. var sqrtMagic = Math.sqrt(magic);
  190. dLat = dLat * 180.0 / (a * (1 - ee) / (magic * sqrtMagic) * pi);
  191. dLng = dLng * 180.0 / (a / sqrtMagic * Math.cos(radLat) * pi);
  192. var mgLat = lat + dLat;
  193. var mgLng = lng + dLng;
  194. var newCoord = {
  195. lng: mgLng,
  196. lat: mgLat
  197. };
  198. return newCoord;
  199. }
  200.  
  201. function transformLat(x, y) {
  202. var ret = -100.0 + 2.0 * x + 3.0 * y + 0.2 * y * y + 0.1 * x * y + 0.2 * Math.sqrt(Math.abs(x));
  203. ret += (20.0 * Math.sin(6.0 * x * pi) + 20.0 * Math.sin(2.0 * x * pi)) * 2.0 / 3.0;
  204. ret += (20.0 * Math.sin(y * pi) + 40.0 * Math.sin(y / 3.0 * pi)) * 2.0 / 3.0;
  205. ret += (160.0 * Math.sin(y / 12.0 * pi) + 320 * Math.sin(y * pi / 30.0)) * 2.0 / 3.0;
  206. return ret;
  207. }
  208.  
  209. function transformLng(x, y) {
  210. var ret = 300.0 + x + 2.0 * y + 0.1 * x * x + 0.1 * x * y + 0.1 * Math.sqrt(Math.abs(x));
  211. ret += (20.0 * Math.sin(6.0 * x * pi) + 20.0 * Math.sin(2.0 * x * pi)) * 2.0 / 3.0;
  212. ret += (20.0 * Math.sin(x * pi) + 40.0 * Math.sin(x / 3.0 * pi)) * 2.0 / 3.0;
  213. ret += (150.0 * Math.sin(x / 12.0 * pi) + 300.0 * Math.sin(x / 30.0 * pi)) * 2.0 / 3.0;
  214. return ret;
  215. }
  216.  
  217. //经纬度转xyz协议瓦片编号
  218. function lonLatToTileNumbers(lon_deg, lat_deg, zoom) {
  219. // 地球半径
  220. /* const r = 6378137;
  221.  
  222. // 地球周长
  223. const C = 2 * Math.PI * 6378137;
  224.  
  225. // 瓦片像素
  226. const titleSize = 256;
  227.  
  228. // 获取某一层级下的分辨率(X,Y方向适)
  229. const getResolution = (n) => {
  230. const tileNums = Math.pow(2, n)
  231. const tileTotalPx = tileNums * titleSize
  232. return C / tileTotalPx
  233. }
  234.  
  235. // 4326转3857
  236. const lngLatMercator = (lng, lat) => {
  237. //注意先转为为弧度制,弧度=角度*Math.PI/180,弧长=弧度*半径
  238. let x = lng * (Math.PI / 180) * r;
  239. let rad = lat * (Math.PI / 180)
  240. let sin = Math.sin(rad)
  241. let y = r / 2 * Math.log((1 + sin) / (1 - sin))
  242. return [x, y]
  243. }
  244.  
  245. // 根据像素坐标及缩放层级计算瓦片行列号
  246. const getTileRowAndCol = (x, y, z) => {
  247. //因为3857与4326坐标原点位于经纬度为零的地方,而瓦片坐标原点位于左上角,所以需要将3857坐标原点转到左上角
  248. x += C / 2;
  249. y = C / 2 - y;
  250. let resolutionX = getResolution(z)//获取某一层级z下的分辨率
  251. let row = Math.floor(x / resolutionX / tileSize)
  252. let col = Math.floor(y / resolutionY / tileSize)
  253. return [row, col]
  254. }
  255.  
  256. return getTileRowAndCol(...lngLatMercator(lon_deg,lat_deg),zoom);*/
  257.  
  258.  
  259.  
  260. /* console.log(lon_deg,lat_deg,zoom);
  261. function lon2tile(lon,zoom) {
  262. return (Math.floor((lon+180)/360*Math.pow(2,zoom)));
  263. }
  264. function lat2tile(lat,zoom) {
  265. return (Math.floor((1-Math.log(Math.tan(lat*Math.PI/180) + 1/Math.cos(lat*Math.PI/180))/Math.PI)/2 *Math.pow(2,zoom)));
  266. }
  267.  
  268. return [lon2tile(lon_deg,zoom),lat2tile(lat_deg,zoom)];*/
  269.  
  270.  
  271.  
  272. var lat_rad = pi / 180 * lat_deg; //math.radians(lat_deg) 角度转弧度
  273. var n = Math.pow(2, zoom);
  274. var xtile = parseInt((lon_deg + 180.0) / 360.0 * n);
  275. var ytile = parseInt((1.0 - Math.asinh(Math.tan(lat_rad)) / pi) / 2.0 * n);
  276. return [xtile, ytile];
  277. }
  278.  
  279. //xyz协议瓦片编号转经纬度
  280. function tileNumbersToLonLat(xtile, ytile, zoom) {
  281. /* function tile2long(x,z) {
  282. return (x/Math.pow(2,z)*360-180);
  283. }
  284.  
  285. function tile2lat(y,z) {
  286. var n=Math.PI-2*Math.PI*y/Math.pow(2,z);
  287. return (180/Math.PI*Math.atan(0.5*(Math.exp(n)-Math.exp(-n))));
  288. }
  289.  
  290. return [tile2long(xtile, zoom),tile2lat(ytile,zoom)];*/
  291.  
  292.  
  293. let n = Math.pow(2, zoom);
  294. let lon_deg = xtile / n * 360.0 - 180.0;
  295. let lat_rad = Math.atan(Math.sinh(pi * (1 - 2 * ytile / n)));
  296.  
  297. let lat_deg = lat_rad * 180.0 / pi;
  298. return [lon_deg, lat_deg];
  299. }
  300. /*
  301. * Created by CntChen 2016.05.04
  302. * 从百度JavaScritp API v2.0 抽取代码,并作少量命名修改
  303. * http://lbsyun.baidu.com/index.php?title=jspopular
  304. * http://api.map.baidu.com/getscript?v=2.0&ak=E4805d16520de693a3fe707cdc962045&t=20160503160001
  305. */
  306.  
  307. // ----- Baidu API start
  308.  
  309. // util function
  310. function Extend(a, b) {
  311. for (var c in b) b.hasOwnProperty(c) && (a[c] = b[c]);
  312. return a;
  313. }
  314. function S(a, b) {
  315. for (var c in b) a[c] = b[c];
  316. }
  317.  
  318. function Xa(a) {
  319. return "string" == typeof a;
  320. }
  321.  
  322. var j = void 0,
  323. p = null;
  324.  
  325. // Point
  326. function H(a, b) {
  327. isNaN(a) && (a = Ib(a), a = isNaN(a) ? 0 : a);
  328. Xa(a) && (a = parseFloat(a));
  329. isNaN(b) && (b = Ib(b), b = isNaN(b) ? 0 : b);
  330. Xa(b) && (b = parseFloat(b));
  331. this.lng = a;
  332. this.lat = b;
  333. }
  334. H.TL = function (a) {
  335. return a && 180 >= a.lng && -180 <= a.lng && 74 >= a.lat && -74 <= a.lat;
  336. };
  337. H.prototype.lb = function (a) {
  338. return a && this.lat == a.lat && this.lng == a.lng;
  339. };
  340.  
  341. // Pixel
  342. function Q(a, b) {
  343. this.x = a || 0;
  344. this.y = b || 0;
  345. this.x = this.x;
  346. this.y = this.y;
  347. }
  348. Q.prototype.lb = function (a) {
  349. return a && a.x == this.x && a.y == this.y;
  350. };
  351.  
  352. // MercatorProjection
  353. function fc() {}
  354. fc.prototype.nh = function () {
  355. aa("lngLatToPoint\u65b9\u6cd5\u672a\u5b9e\u73b0");
  356. };
  357. fc.prototype.wi = function () {
  358. aa("pointToLngLat\u65b9\u6cd5\u672a\u5b9e\u73b0");
  359. };
  360.  
  361. function R() {}
  362. R.prototype = new fc();
  363. Extend(R, {
  364. $O: 6370996.81,
  365. lG: [1.289059486E7, 8362377.87, 5591021, 3481989.83, 1678043.12, 0],
  366. Au: [75, 60, 45, 30, 15, 0],
  367. fP: [[1.410526172116255E-8, 8.98305509648872E-6, -1.9939833816331, 200.9824383106796, -187.2403703815547, 91.6087516669843, -23.38765649603339, 2.57121317296198, -0.03801003308653, 1.73379812E7], [-7.435856389565537E-9, 8.983055097726239E-6, -0.78625201886289, 96.32687599759846, -1.85204757529826, -59.36935905485877, 47.40033549296737, -16.50741931063887, 2.28786674699375, 1.026014486E7], [-3.030883460898826E-8, 8.98305509983578E-6, 0.30071316287616, 59.74293618442277, 7.357984074871, -25.38371002664745, 13.45380521110908, -3.29883767235584, 0.32710905363475, 6856817.37], [-1.981981304930552E-8, 8.983055099779535E-6, 0.03278182852591, 40.31678527705744, 0.65659298677277, -4.44255534477492, 0.85341911805263, 0.12923347998204, -0.04625736007561, 4482777.06], [3.09191371068437E-9, 8.983055096812155E-6, 6.995724062E-5, 23.10934304144901, -2.3663490511E-4, -0.6321817810242, -0.00663494467273, 0.03430082397953, -0.00466043876332, 2555164.4], [2.890871144776878E-9, 8.983055095805407E-6, -3.068298E-8, 7.47137025468032, -3.53937994E-6, -0.02145144861037, -1.234426596E-5, 1.0322952773E-4, -3.23890364E-6, 826088.5]],
  368. iG: [[-0.0015702102444, 111320.7020616939, 1704480524535203, -10338987376042340, 26112667856603880, -35149669176653700, 26595700718403920, -10725012454188240, 1800819912950474, 82.5], [8.277824516172526E-4, 111320.7020463578, 6.477955746671607E8, -4.082003173641316E9, 1.077490566351142E10, -1.517187553151559E10, 1.205306533862167E10, -5.124939663577472E9, 9.133119359512032E8, 67.5], [0.00337398766765, 111320.7020202162, 4481351.045890365, -2.339375119931662E7, 7.968221547186455E7, -1.159649932797253E8, 9.723671115602145E7, -4.366194633752821E7, 8477230.501135234, 52.5], [0.00220636496208, 111320.7020209128, 51751.86112841131, 3796837.749470245, 992013.7397791013, -1221952.21711287, 1340652.697009075, -620943.6990984312, 144416.9293806241, 37.5], [-3.441963504368392E-4, 111320.7020576856, 278.2353980772752, 2485758.690035394, 6070.750963243378, 54821.18345352118, 9540.606633304236, -2710.55326746645, 1405.483844121726, 22.5], [-3.218135878613132E-4, 111320.7020701615, 0.00369383431289, 823725.6402795718, 0.46104986909093, 2351.343141331292, 1.58060784298199, 8.77738589078284, 0.37238884252424, 7.45]],
  369. Z1: function (a, b) {
  370. if (!a || !b) return 0;
  371. var c,
  372. d,
  373. a = this.Fb(a);
  374. if (!a) return 0;
  375. c = this.Tk(a.lng);
  376. d = this.Tk(a.lat);
  377. b = this.Fb(b);
  378. return !b ? 0 : this.Pe(c, this.Tk(b.lng), d, this.Tk(b.lat));
  379. },
  380. Vo: function (a, b) {
  381. if (!a || !b) return 0;
  382. a.lng = this.JD(a.lng, -180, 180);
  383. a.lat = this.ND(a.lat, -74, 74);
  384. b.lng = this.JD(b.lng, -180, 180);
  385. b.lat = this.ND(b.lat, -74, 74);
  386. return this.Pe(this.Tk(a.lng), this.Tk(b.lng), this.Tk(a.lat), this.Tk(b.lat));
  387. },
  388. Fb: function (a) {
  389. if (a === p || a === j) return new H(0, 0);
  390. var b, c;
  391. b = new H(Math.abs(a.lng), Math.abs(a.lat));
  392. for (var d = 0; d < this.lG.length; d++) if (b.lat >= this.lG[d]) {
  393. c = this.fP[d];
  394. break;
  395. }
  396. a = this.gK(a, c);
  397. return a = new H(a.lng.toFixed(6), a.lat.toFixed(6));
  398. },
  399. Eb: function (a) {
  400. if (a === p || a === j || 180 < a.lng || -180 > a.lng || 90 < a.lat || -90 > a.lat) return new H(0, 0);
  401. var b, c;
  402. a.lng = this.JD(a.lng, -180, 180);
  403. a.lat = this.ND(a.lat, -74, 74);
  404. b = new H(a.lng, a.lat);
  405. for (var d = 0; d < this.Au.length; d++) if (b.lat >= this.Au[d]) {
  406. c = this.iG[d];
  407. break;
  408. }
  409.  
  410. // 对疑似bug的修改 start
  411. // by CntChen 2016.05.08
  412. // @2016-09-19 已经得到官方确认为bug:https://cntchen.github.io/2016/05/09/%E7%99%BE%E5%BA%A6JavaScirpt%20%20API%E4%B8%AD%E7%BB%8F%E7%BA%AC%E5%BA%A6%E5%9D%90%E6%A0%87%E8%BD%AC%E7%93%A6%E7%89%87%E5%9D%90%E6%A0%87bug/
  413. if (!c) for (d = 0; d < this.Au.length; d++) if (b.lat <= -this.Au[d]) {
  414. c = this.iG[d];
  415. break;
  416. }
  417. // 对疑似bug的修改 end
  418.  
  419. // Baidu JavaScript 中原本代码, 2016.05.08依然如此
  420. // if (!c)
  421. // for (d = this.Au.length - 1; 0 <= d; d--)
  422. // if (b.lat <= -this.Au[d]) {
  423. // c = this.iG[d];
  424. // break
  425. // }
  426. // Baidu JavaScript 中原本代码 end
  427.  
  428. a = this.gK(a, c);
  429. return a = new H(a.lng.toFixed(2), a.lat.toFixed(2));
  430. },
  431. gK: function (a, b) {
  432. if (a && b) {
  433. var c = b[0] + b[1] * Math.abs(a.lng),
  434. d = Math.abs(a.lat) / b[9],
  435. d = b[2] + b[3] * d + b[4] * d * d + b[5] * d * d * d + b[6] * d * d * d * d + b[7] * d * d * d * d * d + b[8] * d * d * d * d * d * d,
  436. c = c * (0 > a.lng ? -1 : 1),
  437. d = d * (0 > a.lat ? -1 : 1);
  438. return new H(c, d);
  439. }
  440. },
  441. Pe: function (a, b, c, d) {
  442. return this.$O * Math.acos(Math.sin(c) * Math.sin(d) + Math.cos(c) * Math.cos(d) * Math.cos(b - a));
  443. },
  444. Tk: function (a) {
  445. return Math.PI * a / 180;
  446. },
  447. Z3: function (a) {
  448. return 180 * a / Math.PI;
  449. },
  450. ND: function (a, b, c) {
  451. b != p && (a = Math.max(a, b));
  452. c != p && (a = Math.min(a, c));
  453. return a;
  454. },
  455. JD: function (a, b, c) {
  456. for (; a > c;) a -= c - b;
  457. for (; a < b;) a += c - b;
  458. return a;
  459. }
  460. });
  461. Extend(R.prototype, {
  462. Jm: function (a) {
  463. return R.Eb(a);
  464. },
  465. nh: function (a) {
  466. a = R.Eb(a);
  467. return new Q(a.lng, a.lat);
  468. },
  469. qh: function (a) {
  470. return R.Fb(a);
  471. },
  472. wi: function (a) {
  473. a = new H(a.x, a.y);
  474. return R.Fb(a);
  475. },
  476. fc: function (a, b, c, d, e) {
  477. if (a) return a = this.Jm(a, e), b = this.Lc(b), new Q(Math.round((a.lng - c.lng) / b + d.width / 2), Math.round((c.lat - a.lat) / b + d.height / 2));
  478. },
  479. zb: function (a, b, c, d, e) {
  480. if (a) return b = this.Lc(b), this.qh(new H(c.lng + b * (a.x - d.width / 2), c.lat - b * (a.y - d.height / 2)), e);
  481. },
  482. Lc: function (a) {
  483. return Math.pow(2, 18 - a);
  484. }
  485. });
  486.  
  487. var Je = R.prototype;
  488. S(Je, {
  489. lngLatToPoint: Je.nh,
  490. pointToLngLat: Je.wi
  491. });
  492.  
  493. // ----- Baidu API end
  494.  
  495. let BMap = {
  496. Point: H,
  497. Pixel: Q,
  498. MercatorProjection: R
  499. };
  500.  
  501. /*
  502. * Created by CntChen 2016.05.04
  503. * 坐标相关参考文章:
  504. * http://www.cnblogs.com/jz1108/archive/2011/07/02/2095376.html
  505. * http://www.cnblogs.com/janehlp/archive/2012/08/27/2658106.html
  506. * 适用地图:百度
  507. */
  508.  
  509. class TransformClassBaidu {
  510. constructor(levelRange_max, LevelRange_min) {
  511. this.levelMax = levelRange_max;
  512. this.levelMin = LevelRange_min;
  513.  
  514. this.projection = new BMap.MercatorProjection();
  515. }
  516.  
  517. _getRetain(level) {
  518. return Math.pow(2, level - 18);
  519. }
  520.  
  521. /*
  522. * 分辨率,表示水平方向上一个像素点代表的真实距离(m)
  523. * 百度地图18级时的平面坐标就是地图距离原点的距离(m)
  524. * 使用{lng:180, lat:0}时候的pointX是否等于地球赤道长一半来验证
  525. */
  526. getResolution(latitude, level) {
  527. return Math.pow(2, 18 - level) * Math.cos(latitude);
  528. }
  529.  
  530. /*
  531. * 从经纬度到百度平面坐标
  532. */
  533. lnglatToPoint(longitude, latitude) {
  534. let lnglat = new BMap.Point(longitude, latitude);
  535. let point = this.projection.lngLatToPoint(lnglat);
  536.  
  537. // 提取对象的字段并返回
  538. return {
  539. pointX: point.x,
  540. pointY: point.y
  541. };
  542. }
  543.  
  544. /*
  545. * 从百度平面坐标到经纬度
  546. */
  547. pointToLnglat(pointX, pointY) {
  548. let point = new BMap.Pixel(pointX, pointY);
  549. let lnglat = this.projection.pointToLngLat(point);
  550.  
  551. // 不直接返回lnglat对象,因为该对象在百SDK中还有其他属性和方法
  552. // 提取对象的字段后,与其他地图平台统一Lnglat的格式
  553. return {
  554. lng: lnglat.lng,
  555. lat: lnglat.lat
  556. };
  557. }
  558.  
  559. _lngToTileX(longitude, level) {
  560. let point = this.lnglatToPoint(longitude, 0);
  561. let tileX = Math.floor(point.pointX * this._getRetain(level) / 256);
  562.  
  563. return tileX;
  564. }
  565.  
  566. _latToTileY(latitude, level) {
  567. let point = this.lnglatToPoint(0, latitude);
  568. let tileY = Math.floor(point.pointY * this._getRetain(level) / 256);
  569.  
  570. return tileY;
  571. }
  572.  
  573. /*
  574. * 从经纬度获取某一级别瓦片编号
  575. */
  576. lnglatToTile(longitude, latitude, level) {
  577. let tileX = this._lngToTileX(longitude, level);
  578. let tileY = this._latToTileY(latitude, level);
  579.  
  580. return [tileX, tileY];
  581. }
  582.  
  583. _lngToPixelX(longitude, level) {
  584. let tileX = this._lngToTileX(longitude, level);
  585. let point = this.lnglatToPoint(longitude, 0);
  586. let pixelX = Math.floor(point.pointX * this._getRetain(level) - tileX * 256);
  587.  
  588. return pixelX;
  589. }
  590.  
  591. _latToPixelY(latitude, level) {
  592. let tileY = this._latToTileY(latitude, level);
  593. let point = this.lnglatToPoint(0, latitude);
  594. let pixelY = Math.floor(point.pointY * this._getRetain(level) - tileY * 256);
  595.  
  596. return pixelY;
  597. }
  598.  
  599. /*
  600. * 从经纬度到瓦片的像素坐标
  601. */
  602. lnglatToPixel(longitude, latitude, level) {
  603. let pixelX = this._lngToPixelX(longitude, level);
  604. let pixelY = this._latToPixelY(latitude, level);
  605.  
  606. return {
  607. pixelX,
  608. pixelY
  609. };
  610. }
  611.  
  612. _pixelXToLng(pixelX, tileX, level) {
  613. let pointX = (tileX * 256 + pixelX) / this._getRetain(level);
  614. let lnglat = this.pointToLnglat(pointX, 0);
  615.  
  616. return lnglat.lng;
  617. }
  618.  
  619. _pixelYToLat(pixelY, tileY, level) {
  620. let pointY = (tileY * 256 + pixelY) / this._getRetain(level);
  621. let lnglat = this.pointToLnglat(0, pointY);
  622.  
  623. return lnglat.lat;
  624. }
  625.  
  626. /*
  627. * 从某一瓦片的某一像素点到经纬度
  628. */
  629. pixelToLnglat(pixelX, pixelY, tileX, tileY, level) {
  630. let pointX = (tileX * 256 + pixelX) / this._getRetain(level);
  631. let pointY = (tileY * 256 + pixelY) / this._getRetain(level);
  632. let lnglat = this.pointToLnglat(pointX, pointY);
  633.  
  634. return [lnglat.lng, lnglat.lat];
  635. }
  636. }
  637.  
  638. function _classCallCheck(instance, Constructor) {
  639. if (!(instance instanceof Constructor)) {
  640. throw new TypeError("Cannot call a class as a function");
  641. }
  642. }
  643.  
  644. function _defineProperties(target, props) {
  645. for (var i = 0; i < props.length; i++) {
  646. var descriptor = props[i];
  647. descriptor.enumerable = descriptor.enumerable || false;
  648. descriptor.configurable = true;
  649. if ("value" in descriptor) descriptor.writable = true;
  650. Object.defineProperty(target, descriptor.key, descriptor);
  651. }
  652. }
  653.  
  654. function _createClass(Constructor, protoProps, staticProps) {
  655. if (protoProps) _defineProperties(Constructor.prototype, protoProps);
  656. if (staticProps) _defineProperties(Constructor, staticProps);
  657. return Constructor;
  658. }
  659.  
  660. function getDefaultExportFromCjs (x) {
  661. return x && x.__esModule && Object.prototype.hasOwnProperty.call(x, 'default') ? x['default'] : x;
  662. }
  663.  
  664. var _typeof$1 = {exports: {}};
  665.  
  666. (function (module) {
  667. function _typeof(obj) {
  668. "@babel/helpers - typeof";
  669.  
  670. if (typeof Symbol === "function" && typeof Symbol.iterator === "symbol") {
  671. module.exports = _typeof = function _typeof(obj) {
  672. return typeof obj;
  673. };
  674.  
  675. module.exports["default"] = module.exports, module.exports.__esModule = true;
  676. } else {
  677. module.exports = _typeof = function _typeof(obj) {
  678. return obj && typeof Symbol === "function" && obj.constructor === Symbol && obj !== Symbol.prototype ? "symbol" : typeof obj;
  679. };
  680.  
  681. module.exports["default"] = module.exports, module.exports.__esModule = true;
  682. }
  683.  
  684. return _typeof(obj);
  685. }
  686.  
  687. module.exports = _typeof;
  688. module.exports["default"] = module.exports, module.exports.__esModule = true;
  689. }(_typeof$1));
  690.  
  691. var _typeof = /*@__PURE__*/getDefaultExportFromCjs(_typeof$1.exports);
  692.  
  693. function _assertThisInitialized(self) {
  694. if (self === void 0) {
  695. throw new ReferenceError("this hasn't been initialised - super() hasn't been called");
  696. }
  697.  
  698. return self;
  699. }
  700.  
  701. function _possibleConstructorReturn(self, call) {
  702. if (call && (_typeof(call) === "object" || typeof call === "function")) {
  703. return call;
  704. }
  705.  
  706. return _assertThisInitialized(self);
  707. }
  708.  
  709. function _getPrototypeOf(o) {
  710. _getPrototypeOf = Object.setPrototypeOf ? Object.getPrototypeOf : function _getPrototypeOf(o) {
  711. return o.__proto__ || Object.getPrototypeOf(o);
  712. };
  713. return _getPrototypeOf(o);
  714. }
  715.  
  716. function _setPrototypeOf(o, p) {
  717. _setPrototypeOf = Object.setPrototypeOf || function _setPrototypeOf(o, p) {
  718. o.__proto__ = p;
  719. return o;
  720. };
  721.  
  722. return _setPrototypeOf(o, p);
  723. }
  724.  
  725. function _inherits(subClass, superClass) {
  726. if (typeof superClass !== "function" && superClass !== null) {
  727. throw new TypeError("Super expression must either be null or a function");
  728. }
  729.  
  730. subClass.prototype = Object.create(superClass && superClass.prototype, {
  731. constructor: {
  732. value: subClass,
  733. writable: true,
  734. configurable: true
  735. }
  736. });
  737. if (superClass) _setPrototypeOf(subClass, superClass);
  738. }
  739.  
  740. function _arrayWithHoles(arr) {
  741. if (Array.isArray(arr)) return arr;
  742. }
  743.  
  744. function _iterableToArrayLimit(arr, i) {
  745. var _i = arr == null ? null : typeof Symbol !== "undefined" && arr[Symbol.iterator] || arr["@@iterator"];
  746.  
  747. if (_i == null) return;
  748. var _arr = [];
  749. var _n = true;
  750. var _d = false;
  751.  
  752. var _s, _e;
  753.  
  754. try {
  755. for (_i = _i.call(arr); !(_n = (_s = _i.next()).done); _n = true) {
  756. _arr.push(_s.value);
  757.  
  758. if (i && _arr.length === i) break;
  759. }
  760. } catch (err) {
  761. _d = true;
  762. _e = err;
  763. } finally {
  764. try {
  765. if (!_n && _i["return"] != null) _i["return"]();
  766. } finally {
  767. if (_d) throw _e;
  768. }
  769. }
  770.  
  771. return _arr;
  772. }
  773.  
  774. function _arrayLikeToArray(arr, len) {
  775. if (len == null || len > arr.length) len = arr.length;
  776.  
  777. for (var i = 0, arr2 = new Array(len); i < len; i++) {
  778. arr2[i] = arr[i];
  779. }
  780.  
  781. return arr2;
  782. }
  783.  
  784. function _unsupportedIterableToArray(o, minLen) {
  785. if (!o) return;
  786. if (typeof o === "string") return _arrayLikeToArray(o, minLen);
  787. var n = Object.prototype.toString.call(o).slice(8, -1);
  788. if (n === "Object" && o.constructor) n = o.constructor.name;
  789. if (n === "Map" || n === "Set") return Array.from(o);
  790. if (n === "Arguments" || /^(?:Ui|I)nt(?:8|16|32)(?:Clamped)?Array$/.test(n)) return _arrayLikeToArray(o, minLen);
  791. }
  792.  
  793. function _nonIterableRest() {
  794. throw new TypeError("Invalid attempt to destructure non-iterable instance.\nIn order to be iterable, non-array objects must have a [Symbol.iterator]() method.");
  795. }
  796.  
  797. function _slicedToArray(arr, i) {
  798. return _arrayWithHoles(arr) || _iterableToArrayLimit(arr, i) || _unsupportedIterableToArray(arr, i) || _nonIterableRest();
  799. }
  800.  
  801. /**
  802. * Common utilities
  803. * @module glMatrix
  804. */
  805. // Configuration Constants
  806. var EPSILON = 0.000001;
  807. var ARRAY_TYPE = typeof Float32Array !== 'undefined' ? Float32Array : Array;
  808. if (!Math.hypot) Math.hypot = function () {
  809. var y = 0,
  810. i = arguments.length;
  811.  
  812. while (i--) {
  813. y += arguments[i] * arguments[i];
  814. }
  815.  
  816. return Math.sqrt(y);
  817. };
  818.  
  819. /**
  820. * 4 Dimensional Vector
  821. * @module vec4
  822. */
  823.  
  824. /**
  825. * Creates a new, empty vec4
  826. *
  827. * @returns {vec4} a new 4D vector
  828. */
  829.  
  830. function create$2() {
  831. var out = new ARRAY_TYPE(4);
  832.  
  833. if (ARRAY_TYPE != Float32Array) {
  834. out[0] = 0;
  835. out[1] = 0;
  836. out[2] = 0;
  837. out[3] = 0;
  838. }
  839.  
  840. return out;
  841. }
  842. /**
  843. * Scales a vec4 by a scalar number
  844. *
  845. * @param {vec4} out the receiving vector
  846. * @param {ReadonlyVec4} a the vector to scale
  847. * @param {Number} b amount to scale the vector by
  848. * @returns {vec4} out
  849. */
  850.  
  851. function scale$1(out, a, b) {
  852. out[0] = a[0] * b;
  853. out[1] = a[1] * b;
  854. out[2] = a[2] * b;
  855. out[3] = a[3] * b;
  856. return out;
  857. }
  858. /**
  859. * Transforms the vec4 with a mat4.
  860. *
  861. * @param {vec4} out the receiving vector
  862. * @param {ReadonlyVec4} a the vector to transform
  863. * @param {ReadonlyMat4} m matrix to transform with
  864. * @returns {vec4} out
  865. */
  866.  
  867. function transformMat4(out, a, m) {
  868. var x = a[0],
  869. y = a[1],
  870. z = a[2],
  871. w = a[3];
  872. out[0] = m[0] * x + m[4] * y + m[8] * z + m[12] * w;
  873. out[1] = m[1] * x + m[5] * y + m[9] * z + m[13] * w;
  874. out[2] = m[2] * x + m[6] * y + m[10] * z + m[14] * w;
  875. out[3] = m[3] * x + m[7] * y + m[11] * z + m[15] * w;
  876. return out;
  877. }
  878. /**
  879. * Perform some operation over an array of vec4s.
  880. *
  881. * @param {Array} a the array of vectors to iterate over
  882. * @param {Number} stride Number of elements between the start of each vec4. If 0 assumes tightly packed
  883. * @param {Number} offset Number of elements to skip at the beginning of the array
  884. * @param {Number} count Number of vec4s to iterate over. If 0 iterates over entire array
  885. * @param {Function} fn Function to call for each vector in the array
  886. * @param {Object} [arg] additional argument to pass to fn
  887. * @returns {Array} a
  888. * @function
  889. */
  890.  
  891. (function () {
  892. var vec = create$2();
  893. return function (a, stride, offset, count, fn, arg) {
  894. var i, l;
  895.  
  896. if (!stride) {
  897. stride = 4;
  898. }
  899.  
  900. if (!offset) {
  901. offset = 0;
  902. }
  903.  
  904. if (count) {
  905. l = Math.min(count * stride + offset, a.length);
  906. } else {
  907. l = a.length;
  908. }
  909.  
  910. for (i = offset; i < l; i += stride) {
  911. vec[0] = a[i];
  912. vec[1] = a[i + 1];
  913. vec[2] = a[i + 2];
  914. vec[3] = a[i + 3];
  915. fn(vec, vec, arg);
  916. a[i] = vec[0];
  917. a[i + 1] = vec[1];
  918. a[i + 2] = vec[2];
  919. a[i + 3] = vec[3];
  920. }
  921.  
  922. return a;
  923. };
  924. })();
  925.  
  926. function createMat4() {
  927. return [1, 0, 0, 0, 0, 1, 0, 0, 0, 0, 1, 0, 0, 0, 0, 1];
  928. }
  929. function transformVector(matrix, vector) {
  930. var result = transformMat4([], vector, matrix);
  931. scale$1(result, result, 1 / result[3]);
  932. return result;
  933. }
  934.  
  935. /**
  936. * Inverts a mat4
  937. *
  938. * @param {mat4} out the receiving matrix
  939. * @param {ReadonlyMat4} a the source matrix
  940. * @returns {mat4} out
  941. */
  942.  
  943. function invert(out, a) {
  944. var a00 = a[0],
  945. a01 = a[1],
  946. a02 = a[2],
  947. a03 = a[3];
  948. var a10 = a[4],
  949. a11 = a[5],
  950. a12 = a[6],
  951. a13 = a[7];
  952. var a20 = a[8],
  953. a21 = a[9],
  954. a22 = a[10],
  955. a23 = a[11];
  956. var a30 = a[12],
  957. a31 = a[13],
  958. a32 = a[14],
  959. a33 = a[15];
  960. var b00 = a00 * a11 - a01 * a10;
  961. var b01 = a00 * a12 - a02 * a10;
  962. var b02 = a00 * a13 - a03 * a10;
  963. var b03 = a01 * a12 - a02 * a11;
  964. var b04 = a01 * a13 - a03 * a11;
  965. var b05 = a02 * a13 - a03 * a12;
  966. var b06 = a20 * a31 - a21 * a30;
  967. var b07 = a20 * a32 - a22 * a30;
  968. var b08 = a20 * a33 - a23 * a30;
  969. var b09 = a21 * a32 - a22 * a31;
  970. var b10 = a21 * a33 - a23 * a31;
  971. var b11 = a22 * a33 - a23 * a32; // Calculate the determinant
  972.  
  973. var det = b00 * b11 - b01 * b10 + b02 * b09 + b03 * b08 - b04 * b07 + b05 * b06;
  974.  
  975. if (!det) {
  976. return null;
  977. }
  978.  
  979. det = 1.0 / det;
  980. out[0] = (a11 * b11 - a12 * b10 + a13 * b09) * det;
  981. out[1] = (a02 * b10 - a01 * b11 - a03 * b09) * det;
  982. out[2] = (a31 * b05 - a32 * b04 + a33 * b03) * det;
  983. out[3] = (a22 * b04 - a21 * b05 - a23 * b03) * det;
  984. out[4] = (a12 * b08 - a10 * b11 - a13 * b07) * det;
  985. out[5] = (a00 * b11 - a02 * b08 + a03 * b07) * det;
  986. out[6] = (a32 * b02 - a30 * b05 - a33 * b01) * det;
  987. out[7] = (a20 * b05 - a22 * b02 + a23 * b01) * det;
  988. out[8] = (a10 * b10 - a11 * b08 + a13 * b06) * det;
  989. out[9] = (a01 * b08 - a00 * b10 - a03 * b06) * det;
  990. out[10] = (a30 * b04 - a31 * b02 + a33 * b00) * det;
  991. out[11] = (a21 * b02 - a20 * b04 - a23 * b00) * det;
  992. out[12] = (a11 * b07 - a10 * b09 - a12 * b06) * det;
  993. out[13] = (a00 * b09 - a01 * b07 + a02 * b06) * det;
  994. out[14] = (a31 * b01 - a30 * b03 - a32 * b00) * det;
  995. out[15] = (a20 * b03 - a21 * b01 + a22 * b00) * det;
  996. return out;
  997. }
  998. /**
  999. * Multiplies two mat4s
  1000. *
  1001. * @param {mat4} out the receiving matrix
  1002. * @param {ReadonlyMat4} a the first operand
  1003. * @param {ReadonlyMat4} b the second operand
  1004. * @returns {mat4} out
  1005. */
  1006.  
  1007. function multiply(out, a, b) {
  1008. var a00 = a[0],
  1009. a01 = a[1],
  1010. a02 = a[2],
  1011. a03 = a[3];
  1012. var a10 = a[4],
  1013. a11 = a[5],
  1014. a12 = a[6],
  1015. a13 = a[7];
  1016. var a20 = a[8],
  1017. a21 = a[9],
  1018. a22 = a[10],
  1019. a23 = a[11];
  1020. var a30 = a[12],
  1021. a31 = a[13],
  1022. a32 = a[14],
  1023. a33 = a[15]; // Cache only the current line of the second matrix
  1024.  
  1025. var b0 = b[0],
  1026. b1 = b[1],
  1027. b2 = b[2],
  1028. b3 = b[3];
  1029. out[0] = b0 * a00 + b1 * a10 + b2 * a20 + b3 * a30;
  1030. out[1] = b0 * a01 + b1 * a11 + b2 * a21 + b3 * a31;
  1031. out[2] = b0 * a02 + b1 * a12 + b2 * a22 + b3 * a32;
  1032. out[3] = b0 * a03 + b1 * a13 + b2 * a23 + b3 * a33;
  1033. b0 = b[4];
  1034. b1 = b[5];
  1035. b2 = b[6];
  1036. b3 = b[7];
  1037. out[4] = b0 * a00 + b1 * a10 + b2 * a20 + b3 * a30;
  1038. out[5] = b0 * a01 + b1 * a11 + b2 * a21 + b3 * a31;
  1039. out[6] = b0 * a02 + b1 * a12 + b2 * a22 + b3 * a32;
  1040. out[7] = b0 * a03 + b1 * a13 + b2 * a23 + b3 * a33;
  1041. b0 = b[8];
  1042. b1 = b[9];
  1043. b2 = b[10];
  1044. b3 = b[11];
  1045. out[8] = b0 * a00 + b1 * a10 + b2 * a20 + b3 * a30;
  1046. out[9] = b0 * a01 + b1 * a11 + b2 * a21 + b3 * a31;
  1047. out[10] = b0 * a02 + b1 * a12 + b2 * a22 + b3 * a32;
  1048. out[11] = b0 * a03 + b1 * a13 + b2 * a23 + b3 * a33;
  1049. b0 = b[12];
  1050. b1 = b[13];
  1051. b2 = b[14];
  1052. b3 = b[15];
  1053. out[12] = b0 * a00 + b1 * a10 + b2 * a20 + b3 * a30;
  1054. out[13] = b0 * a01 + b1 * a11 + b2 * a21 + b3 * a31;
  1055. out[14] = b0 * a02 + b1 * a12 + b2 * a22 + b3 * a32;
  1056. out[15] = b0 * a03 + b1 * a13 + b2 * a23 + b3 * a33;
  1057. return out;
  1058. }
  1059. /**
  1060. * Translate a mat4 by the given vector
  1061. *
  1062. * @param {mat4} out the receiving matrix
  1063. * @param {ReadonlyMat4} a the matrix to translate
  1064. * @param {ReadonlyVec3} v vector to translate by
  1065. * @returns {mat4} out
  1066. */
  1067.  
  1068. function translate(out, a, v) {
  1069. var x = v[0],
  1070. y = v[1],
  1071. z = v[2];
  1072. var a00, a01, a02, a03;
  1073. var a10, a11, a12, a13;
  1074. var a20, a21, a22, a23;
  1075.  
  1076. if (a === out) {
  1077. out[12] = a[0] * x + a[4] * y + a[8] * z + a[12];
  1078. out[13] = a[1] * x + a[5] * y + a[9] * z + a[13];
  1079. out[14] = a[2] * x + a[6] * y + a[10] * z + a[14];
  1080. out[15] = a[3] * x + a[7] * y + a[11] * z + a[15];
  1081. } else {
  1082. a00 = a[0];
  1083. a01 = a[1];
  1084. a02 = a[2];
  1085. a03 = a[3];
  1086. a10 = a[4];
  1087. a11 = a[5];
  1088. a12 = a[6];
  1089. a13 = a[7];
  1090. a20 = a[8];
  1091. a21 = a[9];
  1092. a22 = a[10];
  1093. a23 = a[11];
  1094. out[0] = a00;
  1095. out[1] = a01;
  1096. out[2] = a02;
  1097. out[3] = a03;
  1098. out[4] = a10;
  1099. out[5] = a11;
  1100. out[6] = a12;
  1101. out[7] = a13;
  1102. out[8] = a20;
  1103. out[9] = a21;
  1104. out[10] = a22;
  1105. out[11] = a23;
  1106. out[12] = a00 * x + a10 * y + a20 * z + a[12];
  1107. out[13] = a01 * x + a11 * y + a21 * z + a[13];
  1108. out[14] = a02 * x + a12 * y + a22 * z + a[14];
  1109. out[15] = a03 * x + a13 * y + a23 * z + a[15];
  1110. }
  1111.  
  1112. return out;
  1113. }
  1114. /**
  1115. * Scales the mat4 by the dimensions in the given vec3 not using vectorization
  1116. *
  1117. * @param {mat4} out the receiving matrix
  1118. * @param {ReadonlyMat4} a the matrix to scale
  1119. * @param {ReadonlyVec3} v the vec3 to scale the matrix by
  1120. * @returns {mat4} out
  1121. **/
  1122.  
  1123. function scale(out, a, v) {
  1124. var x = v[0],
  1125. y = v[1],
  1126. z = v[2];
  1127. out[0] = a[0] * x;
  1128. out[1] = a[1] * x;
  1129. out[2] = a[2] * x;
  1130. out[3] = a[3] * x;
  1131. out[4] = a[4] * y;
  1132. out[5] = a[5] * y;
  1133. out[6] = a[6] * y;
  1134. out[7] = a[7] * y;
  1135. out[8] = a[8] * z;
  1136. out[9] = a[9] * z;
  1137. out[10] = a[10] * z;
  1138. out[11] = a[11] * z;
  1139. out[12] = a[12];
  1140. out[13] = a[13];
  1141. out[14] = a[14];
  1142. out[15] = a[15];
  1143. return out;
  1144. }
  1145. /**
  1146. * Rotates a matrix by the given angle around the X axis
  1147. *
  1148. * @param {mat4} out the receiving matrix
  1149. * @param {ReadonlyMat4} a the matrix to rotate
  1150. * @param {Number} rad the angle to rotate the matrix by
  1151. * @returns {mat4} out
  1152. */
  1153.  
  1154. function rotateX(out, a, rad) {
  1155. var s = Math.sin(rad);
  1156. var c = Math.cos(rad);
  1157. var a10 = a[4];
  1158. var a11 = a[5];
  1159. var a12 = a[6];
  1160. var a13 = a[7];
  1161. var a20 = a[8];
  1162. var a21 = a[9];
  1163. var a22 = a[10];
  1164. var a23 = a[11];
  1165.  
  1166. if (a !== out) {
  1167. // If the source and destination differ, copy the unchanged rows
  1168. out[0] = a[0];
  1169. out[1] = a[1];
  1170. out[2] = a[2];
  1171. out[3] = a[3];
  1172. out[12] = a[12];
  1173. out[13] = a[13];
  1174. out[14] = a[14];
  1175. out[15] = a[15];
  1176. } // Perform axis-specific matrix multiplication
  1177.  
  1178.  
  1179. out[4] = a10 * c + a20 * s;
  1180. out[5] = a11 * c + a21 * s;
  1181. out[6] = a12 * c + a22 * s;
  1182. out[7] = a13 * c + a23 * s;
  1183. out[8] = a20 * c - a10 * s;
  1184. out[9] = a21 * c - a11 * s;
  1185. out[10] = a22 * c - a12 * s;
  1186. out[11] = a23 * c - a13 * s;
  1187. return out;
  1188. }
  1189. /**
  1190. * Rotates a matrix by the given angle around the Z axis
  1191. *
  1192. * @param {mat4} out the receiving matrix
  1193. * @param {ReadonlyMat4} a the matrix to rotate
  1194. * @param {Number} rad the angle to rotate the matrix by
  1195. * @returns {mat4} out
  1196. */
  1197.  
  1198. function rotateZ(out, a, rad) {
  1199. var s = Math.sin(rad);
  1200. var c = Math.cos(rad);
  1201. var a00 = a[0];
  1202. var a01 = a[1];
  1203. var a02 = a[2];
  1204. var a03 = a[3];
  1205. var a10 = a[4];
  1206. var a11 = a[5];
  1207. var a12 = a[6];
  1208. var a13 = a[7];
  1209.  
  1210. if (a !== out) {
  1211. // If the source and destination differ, copy the unchanged last row
  1212. out[8] = a[8];
  1213. out[9] = a[9];
  1214. out[10] = a[10];
  1215. out[11] = a[11];
  1216. out[12] = a[12];
  1217. out[13] = a[13];
  1218. out[14] = a[14];
  1219. out[15] = a[15];
  1220. } // Perform axis-specific matrix multiplication
  1221.  
  1222.  
  1223. out[0] = a00 * c + a10 * s;
  1224. out[1] = a01 * c + a11 * s;
  1225. out[2] = a02 * c + a12 * s;
  1226. out[3] = a03 * c + a13 * s;
  1227. out[4] = a10 * c - a00 * s;
  1228. out[5] = a11 * c - a01 * s;
  1229. out[6] = a12 * c - a02 * s;
  1230. out[7] = a13 * c - a03 * s;
  1231. return out;
  1232. }
  1233. /**
  1234. * Generates a perspective projection matrix with the given bounds.
  1235. * Passing null/undefined/no value for far will generate infinite projection matrix.
  1236. *
  1237. * @param {mat4} out mat4 frustum matrix will be written into
  1238. * @param {number} fovy Vertical field of view in radians
  1239. * @param {number} aspect Aspect ratio. typically viewport width/height
  1240. * @param {number} near Near bound of the frustum
  1241. * @param {number} far Far bound of the frustum, can be null or Infinity
  1242. * @returns {mat4} out
  1243. */
  1244.  
  1245. function perspective(out, fovy, aspect, near, far) {
  1246. var f = 1.0 / Math.tan(fovy / 2),
  1247. nf;
  1248. out[0] = f / aspect;
  1249. out[1] = 0;
  1250. out[2] = 0;
  1251. out[3] = 0;
  1252. out[4] = 0;
  1253. out[5] = f;
  1254. out[6] = 0;
  1255. out[7] = 0;
  1256. out[8] = 0;
  1257. out[9] = 0;
  1258. out[11] = -1;
  1259. out[12] = 0;
  1260. out[13] = 0;
  1261. out[15] = 0;
  1262.  
  1263. if (far != null && far !== Infinity) {
  1264. nf = 1 / (near - far);
  1265. out[10] = (far + near) * nf;
  1266. out[14] = 2 * far * near * nf;
  1267. } else {
  1268. out[10] = -1;
  1269. out[14] = -2 * near;
  1270. }
  1271.  
  1272. return out;
  1273. }
  1274. /**
  1275. * Returns whether or not the matrices have approximately the same elements in the same position.
  1276. *
  1277. * @param {ReadonlyMat4} a The first matrix.
  1278. * @param {ReadonlyMat4} b The second matrix.
  1279. * @returns {Boolean} True if the matrices are equal, false otherwise.
  1280. */
  1281.  
  1282. function equals(a, b) {
  1283. var a0 = a[0],
  1284. a1 = a[1],
  1285. a2 = a[2],
  1286. a3 = a[3];
  1287. var a4 = a[4],
  1288. a5 = a[5],
  1289. a6 = a[6],
  1290. a7 = a[7];
  1291. var a8 = a[8],
  1292. a9 = a[9],
  1293. a10 = a[10],
  1294. a11 = a[11];
  1295. var a12 = a[12],
  1296. a13 = a[13],
  1297. a14 = a[14],
  1298. a15 = a[15];
  1299. var b0 = b[0],
  1300. b1 = b[1],
  1301. b2 = b[2],
  1302. b3 = b[3];
  1303. var b4 = b[4],
  1304. b5 = b[5],
  1305. b6 = b[6],
  1306. b7 = b[7];
  1307. var b8 = b[8],
  1308. b9 = b[9],
  1309. b10 = b[10],
  1310. b11 = b[11];
  1311. var b12 = b[12],
  1312. b13 = b[13],
  1313. b14 = b[14],
  1314. b15 = b[15];
  1315. return Math.abs(a0 - b0) <= EPSILON * Math.max(1.0, Math.abs(a0), Math.abs(b0)) && Math.abs(a1 - b1) <= EPSILON * Math.max(1.0, Math.abs(a1), Math.abs(b1)) && Math.abs(a2 - b2) <= EPSILON * Math.max(1.0, Math.abs(a2), Math.abs(b2)) && Math.abs(a3 - b3) <= EPSILON * Math.max(1.0, Math.abs(a3), Math.abs(b3)) && Math.abs(a4 - b4) <= EPSILON * Math.max(1.0, Math.abs(a4), Math.abs(b4)) && Math.abs(a5 - b5) <= EPSILON * Math.max(1.0, Math.abs(a5), Math.abs(b5)) && Math.abs(a6 - b6) <= EPSILON * Math.max(1.0, Math.abs(a6), Math.abs(b6)) && Math.abs(a7 - b7) <= EPSILON * Math.max(1.0, Math.abs(a7), Math.abs(b7)) && Math.abs(a8 - b8) <= EPSILON * Math.max(1.0, Math.abs(a8), Math.abs(b8)) && Math.abs(a9 - b9) <= EPSILON * Math.max(1.0, Math.abs(a9), Math.abs(b9)) && Math.abs(a10 - b10) <= EPSILON * Math.max(1.0, Math.abs(a10), Math.abs(b10)) && Math.abs(a11 - b11) <= EPSILON * Math.max(1.0, Math.abs(a11), Math.abs(b11)) && Math.abs(a12 - b12) <= EPSILON * Math.max(1.0, Math.abs(a12), Math.abs(b12)) && Math.abs(a13 - b13) <= EPSILON * Math.max(1.0, Math.abs(a13), Math.abs(b13)) && Math.abs(a14 - b14) <= EPSILON * Math.max(1.0, Math.abs(a14), Math.abs(b14)) && Math.abs(a15 - b15) <= EPSILON * Math.max(1.0, Math.abs(a15), Math.abs(b15));
  1316. }
  1317.  
  1318. /**
  1319. * 2 Dimensional Vector
  1320. * @module vec2
  1321. */
  1322.  
  1323. /**
  1324. * Creates a new, empty vec2
  1325. *
  1326. * @returns {vec2} a new 2D vector
  1327. */
  1328.  
  1329. function create$1() {
  1330. var out = new ARRAY_TYPE(2);
  1331.  
  1332. if (ARRAY_TYPE != Float32Array) {
  1333. out[0] = 0;
  1334. out[1] = 0;
  1335. }
  1336.  
  1337. return out;
  1338. }
  1339. /**
  1340. * Adds two vec2's
  1341. *
  1342. * @param {vec2} out the receiving vector
  1343. * @param {ReadonlyVec2} a the first operand
  1344. * @param {ReadonlyVec2} b the second operand
  1345. * @returns {vec2} out
  1346. */
  1347.  
  1348. function add(out, a, b) {
  1349. out[0] = a[0] + b[0];
  1350. out[1] = a[1] + b[1];
  1351. return out;
  1352. }
  1353. /**
  1354. * Negates the components of a vec2
  1355. *
  1356. * @param {vec2} out the receiving vector
  1357. * @param {ReadonlyVec2} a vector to negate
  1358. * @returns {vec2} out
  1359. */
  1360.  
  1361. function negate$1(out, a) {
  1362. out[0] = -a[0];
  1363. out[1] = -a[1];
  1364. return out;
  1365. }
  1366. /**
  1367. * Performs a linear interpolation between two vec2's
  1368. *
  1369. * @param {vec2} out the receiving vector
  1370. * @param {ReadonlyVec2} a the first operand
  1371. * @param {ReadonlyVec2} b the second operand
  1372. * @param {Number} t interpolation amount, in the range [0-1], between the two inputs
  1373. * @returns {vec2} out
  1374. */
  1375.  
  1376. function lerp(out, a, b, t) {
  1377. var ax = a[0],
  1378. ay = a[1];
  1379. out[0] = ax + t * (b[0] - ax);
  1380. out[1] = ay + t * (b[1] - ay);
  1381. return out;
  1382. }
  1383. /**
  1384. * Perform some operation over an array of vec2s.
  1385. *
  1386. * @param {Array} a the array of vectors to iterate over
  1387. * @param {Number} stride Number of elements between the start of each vec2. If 0 assumes tightly packed
  1388. * @param {Number} offset Number of elements to skip at the beginning of the array
  1389. * @param {Number} count Number of vec2s to iterate over. If 0 iterates over entire array
  1390. * @param {Function} fn Function to call for each vector in the array
  1391. * @param {Object} [arg] additional argument to pass to fn
  1392. * @returns {Array} a
  1393. * @function
  1394. */
  1395.  
  1396. (function () {
  1397. var vec = create$1();
  1398. return function (a, stride, offset, count, fn, arg) {
  1399. var i, l;
  1400.  
  1401. if (!stride) {
  1402. stride = 2;
  1403. }
  1404.  
  1405. if (!offset) {
  1406. offset = 0;
  1407. }
  1408.  
  1409. if (count) {
  1410. l = Math.min(count * stride + offset, a.length);
  1411. } else {
  1412. l = a.length;
  1413. }
  1414.  
  1415. for (i = offset; i < l; i += stride) {
  1416. vec[0] = a[i];
  1417. vec[1] = a[i + 1];
  1418. fn(vec, vec, arg);
  1419. a[i] = vec[0];
  1420. a[i + 1] = vec[1];
  1421. }
  1422.  
  1423. return a;
  1424. };
  1425. })();
  1426.  
  1427. /**
  1428. * 3 Dimensional Vector
  1429. * @module vec3
  1430. */
  1431.  
  1432. /**
  1433. * Creates a new, empty vec3
  1434. *
  1435. * @returns {vec3} a new 3D vector
  1436. */
  1437.  
  1438. function create() {
  1439. var out = new ARRAY_TYPE(3);
  1440.  
  1441. if (ARRAY_TYPE != Float32Array) {
  1442. out[0] = 0;
  1443. out[1] = 0;
  1444. out[2] = 0;
  1445. }
  1446.  
  1447. return out;
  1448. }
  1449. /**
  1450. * Negates the components of a vec3
  1451. *
  1452. * @param {vec3} out the receiving vector
  1453. * @param {ReadonlyVec3} a vector to negate
  1454. * @returns {vec3} out
  1455. */
  1456.  
  1457. function negate(out, a) {
  1458. out[0] = -a[0];
  1459. out[1] = -a[1];
  1460. out[2] = -a[2];
  1461. return out;
  1462. }
  1463. /**
  1464. * Perform some operation over an array of vec3s.
  1465. *
  1466. * @param {Array} a the array of vectors to iterate over
  1467. * @param {Number} stride Number of elements between the start of each vec3. If 0 assumes tightly packed
  1468. * @param {Number} offset Number of elements to skip at the beginning of the array
  1469. * @param {Number} count Number of vec3s to iterate over. If 0 iterates over entire array
  1470. * @param {Function} fn Function to call for each vector in the array
  1471. * @param {Object} [arg] additional argument to pass to fn
  1472. * @returns {Array} a
  1473. * @function
  1474. */
  1475.  
  1476. (function () {
  1477. var vec = create();
  1478. return function (a, stride, offset, count, fn, arg) {
  1479. var i, l;
  1480.  
  1481. if (!stride) {
  1482. stride = 3;
  1483. }
  1484.  
  1485. if (!offset) {
  1486. offset = 0;
  1487. }
  1488.  
  1489. if (count) {
  1490. l = Math.min(count * stride + offset, a.length);
  1491. } else {
  1492. l = a.length;
  1493. }
  1494.  
  1495. for (i = offset; i < l; i += stride) {
  1496. vec[0] = a[i];
  1497. vec[1] = a[i + 1];
  1498. vec[2] = a[i + 2];
  1499. fn(vec, vec, arg);
  1500. a[i] = vec[0];
  1501. a[i + 1] = vec[1];
  1502. a[i + 2] = vec[2];
  1503. }
  1504.  
  1505. return a;
  1506. };
  1507. })();
  1508.  
  1509. function assert(condition, message) {
  1510. if (!condition) {
  1511. throw new Error(message || 'viewport-mercator-project: assertion failed.');
  1512. }
  1513. }
  1514.  
  1515. var PI$1 = Math.PI;
  1516. var PI_4 = PI$1 / 4;
  1517. var DEGREES_TO_RADIANS$1 = PI$1 / 180;
  1518. var RADIANS_TO_DEGREES = 180 / PI$1;
  1519. var TILE_SIZE$1 = 512;
  1520. var EARTH_CIRCUMFERENCE$1 = 40.03e6;
  1521. var DEFAULT_ALTITUDE = 1.5;
  1522. function zoomToScale$1(zoom) {
  1523. return Math.pow(2, zoom);
  1524. }
  1525. function lngLatToWorld(_ref, scale) {
  1526. var _ref2 = _slicedToArray(_ref, 2),
  1527. lng = _ref2[0],
  1528. lat = _ref2[1];
  1529.  
  1530. assert(Number.isFinite(lng) && Number.isFinite(scale));
  1531. assert(Number.isFinite(lat) && lat >= -90 && lat <= 90, 'invalid latitude');
  1532. scale *= TILE_SIZE$1;
  1533. var lambda2 = lng * DEGREES_TO_RADIANS$1;
  1534. var phi2 = lat * DEGREES_TO_RADIANS$1;
  1535. var x = scale * (lambda2 + PI$1) / (2 * PI$1);
  1536. var y = scale * (PI$1 - Math.log(Math.tan(PI_4 + phi2 * 0.5))) / (2 * PI$1);
  1537. return [x, y];
  1538. }
  1539. function worldToLngLat(_ref3, scale) {
  1540. var _ref4 = _slicedToArray(_ref3, 2),
  1541. x = _ref4[0],
  1542. y = _ref4[1];
  1543.  
  1544. scale *= TILE_SIZE$1;
  1545. var lambda2 = x / scale * (2 * PI$1) - PI$1;
  1546. var phi2 = 2 * (Math.atan(Math.exp(PI$1 - y / scale * (2 * PI$1))) - PI_4);
  1547. return [lambda2 * RADIANS_TO_DEGREES, phi2 * RADIANS_TO_DEGREES];
  1548. }
  1549. function getDistanceScales$1(_ref6) {
  1550. var latitude = _ref6.latitude,
  1551. longitude = _ref6.longitude,
  1552. zoom = _ref6.zoom,
  1553. scale = _ref6.scale,
  1554. _ref6$highPrecision = _ref6.highPrecision,
  1555. highPrecision = _ref6$highPrecision === void 0 ? false : _ref6$highPrecision;
  1556. scale = scale !== undefined ? scale : zoomToScale$1(zoom);
  1557. assert(Number.isFinite(latitude) && Number.isFinite(longitude) && Number.isFinite(scale));
  1558. var result = {};
  1559. var worldSize = TILE_SIZE$1 * scale;
  1560. var latCosine = Math.cos(latitude * DEGREES_TO_RADIANS$1);
  1561. var pixelsPerDegreeX = worldSize / 360;
  1562. var pixelsPerDegreeY = pixelsPerDegreeX / latCosine;
  1563. var altPixelsPerMeter = worldSize / EARTH_CIRCUMFERENCE$1 / latCosine;
  1564. result.pixelsPerMeter = [altPixelsPerMeter, -altPixelsPerMeter, altPixelsPerMeter];
  1565. result.metersPerPixel = [1 / altPixelsPerMeter, -1 / altPixelsPerMeter, 1 / altPixelsPerMeter];
  1566. result.pixelsPerDegree = [pixelsPerDegreeX, -pixelsPerDegreeY, altPixelsPerMeter];
  1567. result.degreesPerPixel = [1 / pixelsPerDegreeX, -1 / pixelsPerDegreeY, 1 / altPixelsPerMeter];
  1568.  
  1569. if (highPrecision) {
  1570. var latCosine2 = DEGREES_TO_RADIANS$1 * Math.tan(latitude * DEGREES_TO_RADIANS$1) / latCosine;
  1571. var pixelsPerDegreeY2 = pixelsPerDegreeX * latCosine2 / 2;
  1572. var altPixelsPerDegree2 = worldSize / EARTH_CIRCUMFERENCE$1 * latCosine2;
  1573. var altPixelsPerMeter2 = altPixelsPerDegree2 / pixelsPerDegreeY * altPixelsPerMeter;
  1574. result.pixelsPerDegree2 = [0, -pixelsPerDegreeY2, altPixelsPerDegree2];
  1575. result.pixelsPerMeter2 = [altPixelsPerMeter2, 0, altPixelsPerMeter2];
  1576. }
  1577.  
  1578. return result;
  1579. }
  1580. function getViewMatrix(_ref7) {
  1581. var height = _ref7.height,
  1582. pitch = _ref7.pitch,
  1583. bearing = _ref7.bearing,
  1584. altitude = _ref7.altitude,
  1585. _ref7$center = _ref7.center,
  1586. center = _ref7$center === void 0 ? null : _ref7$center,
  1587. _ref7$flipY = _ref7.flipY,
  1588. flipY = _ref7$flipY === void 0 ? false : _ref7$flipY;
  1589. var vm = createMat4();
  1590. translate(vm, vm, [0, 0, -altitude]);
  1591. scale(vm, vm, [1, 1, 1 / height]);
  1592. rotateX(vm, vm, -pitch * DEGREES_TO_RADIANS$1);
  1593. rotateZ(vm, vm, bearing * DEGREES_TO_RADIANS$1);
  1594.  
  1595. if (flipY) {
  1596. scale(vm, vm, [1, -1, 1]);
  1597. }
  1598.  
  1599. if (center) {
  1600. translate(vm, vm, negate([], center));
  1601. }
  1602.  
  1603. return vm;
  1604. }
  1605. function getProjectionParameters(_ref8) {
  1606. var width = _ref8.width,
  1607. height = _ref8.height,
  1608. _ref8$altitude = _ref8.altitude,
  1609. altitude = _ref8$altitude === void 0 ? DEFAULT_ALTITUDE : _ref8$altitude,
  1610. _ref8$pitch = _ref8.pitch,
  1611. pitch = _ref8$pitch === void 0 ? 0 : _ref8$pitch,
  1612. _ref8$nearZMultiplier = _ref8.nearZMultiplier,
  1613. nearZMultiplier = _ref8$nearZMultiplier === void 0 ? 1 : _ref8$nearZMultiplier,
  1614. _ref8$farZMultiplier = _ref8.farZMultiplier,
  1615. farZMultiplier = _ref8$farZMultiplier === void 0 ? 1 : _ref8$farZMultiplier;
  1616. var pitchRadians = pitch * DEGREES_TO_RADIANS$1;
  1617. var halfFov = Math.atan(0.5 / altitude);
  1618. var topHalfSurfaceDistance = Math.sin(halfFov) * altitude / Math.sin(Math.PI / 2 - pitchRadians - halfFov);
  1619. var farZ = Math.cos(Math.PI / 2 - pitchRadians) * topHalfSurfaceDistance + altitude;
  1620. return {
  1621. fov: 2 * Math.atan(height / 2 / altitude),
  1622. aspect: width / height,
  1623. focalDistance: altitude,
  1624. near: nearZMultiplier,
  1625. far: farZ * farZMultiplier
  1626. };
  1627. }
  1628. function getProjectionMatrix(_ref9) {
  1629. var width = _ref9.width,
  1630. height = _ref9.height,
  1631. pitch = _ref9.pitch,
  1632. altitude = _ref9.altitude,
  1633. nearZMultiplier = _ref9.nearZMultiplier,
  1634. farZMultiplier = _ref9.farZMultiplier;
  1635.  
  1636. var _getProjectionParamet = getProjectionParameters({
  1637. width: width,
  1638. height: height,
  1639. altitude: altitude,
  1640. pitch: pitch,
  1641. nearZMultiplier: nearZMultiplier,
  1642. farZMultiplier: farZMultiplier
  1643. }),
  1644. fov = _getProjectionParamet.fov,
  1645. aspect = _getProjectionParamet.aspect,
  1646. near = _getProjectionParamet.near,
  1647. far = _getProjectionParamet.far;
  1648.  
  1649. var projectionMatrix = perspective([], fov, aspect, near, far);
  1650. return projectionMatrix;
  1651. }
  1652. function worldToPixels(xyz, pixelProjectionMatrix) {
  1653. var _xyz2 = _slicedToArray(xyz, 3),
  1654. x = _xyz2[0],
  1655. y = _xyz2[1],
  1656. _xyz2$ = _xyz2[2],
  1657. z = _xyz2$ === void 0 ? 0 : _xyz2$;
  1658.  
  1659. assert(Number.isFinite(x) && Number.isFinite(y) && Number.isFinite(z));
  1660. return transformVector(pixelProjectionMatrix, [x, y, z, 1]);
  1661. }
  1662. function pixelsToWorld(xyz, pixelUnprojectionMatrix) {
  1663. var targetZ = arguments.length > 2 && arguments[2] !== undefined ? arguments[2] : 0;
  1664.  
  1665. var _xyz3 = _slicedToArray(xyz, 3),
  1666. x = _xyz3[0],
  1667. y = _xyz3[1],
  1668. z = _xyz3[2];
  1669.  
  1670. assert(Number.isFinite(x) && Number.isFinite(y), 'invalid pixel coordinate');
  1671.  
  1672. if (Number.isFinite(z)) {
  1673. var coord = transformVector(pixelUnprojectionMatrix, [x, y, z, 1]);
  1674. return coord;
  1675. }
  1676.  
  1677. var coord0 = transformVector(pixelUnprojectionMatrix, [x, y, 0, 1]);
  1678. var coord1 = transformVector(pixelUnprojectionMatrix, [x, y, 1, 1]);
  1679. var z0 = coord0[2];
  1680. var z1 = coord1[2];
  1681. var t = z0 === z1 ? 0 : ((targetZ || 0) - z0) / (z1 - z0);
  1682. return lerp([], coord0, coord1, t);
  1683. }
  1684.  
  1685. var IDENTITY = createMat4();
  1686.  
  1687. var Viewport = function () {
  1688. function Viewport() {
  1689. var _ref = arguments.length > 0 && arguments[0] !== undefined ? arguments[0] : {},
  1690. width = _ref.width,
  1691. height = _ref.height,
  1692. _ref$viewMatrix = _ref.viewMatrix,
  1693. viewMatrix = _ref$viewMatrix === void 0 ? IDENTITY : _ref$viewMatrix,
  1694. _ref$projectionMatrix = _ref.projectionMatrix,
  1695. projectionMatrix = _ref$projectionMatrix === void 0 ? IDENTITY : _ref$projectionMatrix;
  1696.  
  1697. _classCallCheck(this, Viewport);
  1698.  
  1699. this.width = width || 1;
  1700. this.height = height || 1;
  1701. this.scale = 1;
  1702. this.pixelsPerMeter = 1;
  1703. this.viewMatrix = viewMatrix;
  1704. this.projectionMatrix = projectionMatrix;
  1705. var vpm = createMat4();
  1706. multiply(vpm, vpm, this.projectionMatrix);
  1707. multiply(vpm, vpm, this.viewMatrix);
  1708. this.viewProjectionMatrix = vpm;
  1709. var m = createMat4();
  1710. scale(m, m, [this.width / 2, -this.height / 2, 1]);
  1711. translate(m, m, [1, -1, 0]);
  1712. multiply(m, m, this.viewProjectionMatrix);
  1713. var mInverse = invert(createMat4(), m);
  1714.  
  1715. if (!mInverse) {
  1716. throw new Error('Pixel project matrix not invertible');
  1717. }
  1718.  
  1719. this.pixelProjectionMatrix = m;
  1720. this.pixelUnprojectionMatrix = mInverse;
  1721. this.equals = this.equals.bind(this);
  1722. this.project = this.project.bind(this);
  1723. this.unproject = this.unproject.bind(this);
  1724. this.projectPosition = this.projectPosition.bind(this);
  1725. this.unprojectPosition = this.unprojectPosition.bind(this);
  1726. this.projectFlat = this.projectFlat.bind(this);
  1727. this.unprojectFlat = this.unprojectFlat.bind(this);
  1728. }
  1729.  
  1730. _createClass(Viewport, [{
  1731. key: "equals",
  1732. value: function equals$1(viewport) {
  1733. if (!(viewport instanceof Viewport)) {
  1734. return false;
  1735. }
  1736.  
  1737. return viewport.width === this.width && viewport.height === this.height && equals(viewport.projectionMatrix, this.projectionMatrix) && equals(viewport.viewMatrix, this.viewMatrix);
  1738. }
  1739. }, {
  1740. key: "project",
  1741. value: function project(xyz) {
  1742. var _ref2 = arguments.length > 1 && arguments[1] !== undefined ? arguments[1] : {},
  1743. _ref2$topLeft = _ref2.topLeft,
  1744. topLeft = _ref2$topLeft === void 0 ? true : _ref2$topLeft;
  1745.  
  1746. var worldPosition = this.projectPosition(xyz);
  1747. var coord = worldToPixels(worldPosition, this.pixelProjectionMatrix);
  1748.  
  1749. var _coord = _slicedToArray(coord, 2),
  1750. x = _coord[0],
  1751. y = _coord[1];
  1752.  
  1753. var y2 = topLeft ? y : this.height - y;
  1754. return xyz.length === 2 ? [x, y2] : [x, y2, coord[2]];
  1755. }
  1756. }, {
  1757. key: "unproject",
  1758. value: function unproject(xyz) {
  1759. var _ref3 = arguments.length > 1 && arguments[1] !== undefined ? arguments[1] : {},
  1760. _ref3$topLeft = _ref3.topLeft,
  1761. topLeft = _ref3$topLeft === void 0 ? true : _ref3$topLeft,
  1762. targetZ = _ref3.targetZ;
  1763.  
  1764. var _xyz = _slicedToArray(xyz, 3),
  1765. x = _xyz[0],
  1766. y = _xyz[1],
  1767. z = _xyz[2];
  1768.  
  1769. var y2 = topLeft ? y : this.height - y;
  1770. var targetZWorld = targetZ && targetZ * this.pixelsPerMeter;
  1771. var coord = pixelsToWorld([x, y2, z], this.pixelUnprojectionMatrix, targetZWorld);
  1772.  
  1773. var _this$unprojectPositi = this.unprojectPosition(coord),
  1774. _this$unprojectPositi2 = _slicedToArray(_this$unprojectPositi, 3),
  1775. X = _this$unprojectPositi2[0],
  1776. Y = _this$unprojectPositi2[1],
  1777. Z = _this$unprojectPositi2[2];
  1778.  
  1779. if (Number.isFinite(z)) {
  1780. return [X, Y, Z];
  1781. }
  1782.  
  1783. return Number.isFinite(targetZ) ? [X, Y, targetZ] : [X, Y];
  1784. }
  1785. }, {
  1786. key: "projectPosition",
  1787. value: function projectPosition(xyz) {
  1788. var _this$projectFlat = this.projectFlat(xyz),
  1789. _this$projectFlat2 = _slicedToArray(_this$projectFlat, 2),
  1790. X = _this$projectFlat2[0],
  1791. Y = _this$projectFlat2[1];
  1792.  
  1793. var Z = (xyz[2] || 0) * this.pixelsPerMeter;
  1794. return [X, Y, Z];
  1795. }
  1796. }, {
  1797. key: "unprojectPosition",
  1798. value: function unprojectPosition(xyz) {
  1799. var _this$unprojectFlat = this.unprojectFlat(xyz),
  1800. _this$unprojectFlat2 = _slicedToArray(_this$unprojectFlat, 2),
  1801. X = _this$unprojectFlat2[0],
  1802. Y = _this$unprojectFlat2[1];
  1803.  
  1804. var Z = (xyz[2] || 0) / this.pixelsPerMeter;
  1805. return [X, Y, Z];
  1806. }
  1807. }, {
  1808. key: "projectFlat",
  1809. value: function projectFlat(xyz) {
  1810. arguments.length > 1 && arguments[1] !== undefined ? arguments[1] : this.scale;
  1811. return xyz;
  1812. }
  1813. }, {
  1814. key: "unprojectFlat",
  1815. value: function unprojectFlat(xyz) {
  1816. arguments.length > 1 && arguments[1] !== undefined ? arguments[1] : this.scale;
  1817. return xyz;
  1818. }
  1819. }]);
  1820.  
  1821. return Viewport;
  1822. }();
  1823.  
  1824. function fitBounds(_ref) {
  1825. var width = _ref.width,
  1826. height = _ref.height,
  1827. bounds = _ref.bounds,
  1828. _ref$minExtent = _ref.minExtent,
  1829. minExtent = _ref$minExtent === void 0 ? 0 : _ref$minExtent,
  1830. _ref$maxZoom = _ref.maxZoom,
  1831. maxZoom = _ref$maxZoom === void 0 ? 24 : _ref$maxZoom,
  1832. _ref$padding = _ref.padding,
  1833. padding = _ref$padding === void 0 ? 0 : _ref$padding,
  1834. _ref$offset = _ref.offset,
  1835. offset = _ref$offset === void 0 ? [0, 0] : _ref$offset;
  1836.  
  1837. var _bounds = _slicedToArray(bounds, 2),
  1838. _bounds$ = _slicedToArray(_bounds[0], 2),
  1839. west = _bounds$[0],
  1840. south = _bounds$[1],
  1841. _bounds$2 = _slicedToArray(_bounds[1], 2),
  1842. east = _bounds$2[0],
  1843. north = _bounds$2[1];
  1844.  
  1845. if (Number.isFinite(padding)) {
  1846. var p = padding;
  1847. padding = {
  1848. top: p,
  1849. bottom: p,
  1850. left: p,
  1851. right: p
  1852. };
  1853. } else {
  1854. assert(Number.isFinite(padding.top) && Number.isFinite(padding.bottom) && Number.isFinite(padding.left) && Number.isFinite(padding.right));
  1855. }
  1856.  
  1857. var viewport = new WebMercatorViewport({
  1858. width: width,
  1859. height: height,
  1860. longitude: 0,
  1861. latitude: 0,
  1862. zoom: 0
  1863. });
  1864. var nw = viewport.project([west, north]);
  1865. var se = viewport.project([east, south]);
  1866. var size = [Math.max(Math.abs(se[0] - nw[0]), minExtent), Math.max(Math.abs(se[1] - nw[1]), minExtent)];
  1867. var targetSize = [width - padding.left - padding.right - Math.abs(offset[0]) * 2, height - padding.top - padding.bottom - Math.abs(offset[1]) * 2];
  1868. assert(targetSize[0] > 0 && targetSize[1] > 0);
  1869. var scaleX = targetSize[0] / size[0];
  1870. var scaleY = targetSize[1] / size[1];
  1871. var offsetX = (padding.right - padding.left) / 2 / scaleX;
  1872. var offsetY = (padding.bottom - padding.top) / 2 / scaleY;
  1873. var center = [(se[0] + nw[0]) / 2 + offsetX, (se[1] + nw[1]) / 2 + offsetY];
  1874. var centerLngLat = viewport.unproject(center);
  1875. var zoom = viewport.zoom + Math.log2(Math.abs(Math.min(scaleX, scaleY)));
  1876. return {
  1877. longitude: centerLngLat[0],
  1878. latitude: centerLngLat[1],
  1879. zoom: Math.min(zoom, maxZoom)
  1880. };
  1881. }
  1882.  
  1883. var WebMercatorViewport = function (_Viewport) {
  1884. _inherits(WebMercatorViewport, _Viewport);
  1885.  
  1886. function WebMercatorViewport() {
  1887. var _this;
  1888.  
  1889. var _ref = arguments.length > 0 && arguments[0] !== undefined ? arguments[0] : {},
  1890. width = _ref.width,
  1891. height = _ref.height,
  1892. _ref$latitude = _ref.latitude,
  1893. latitude = _ref$latitude === void 0 ? 0 : _ref$latitude,
  1894. _ref$longitude = _ref.longitude,
  1895. longitude = _ref$longitude === void 0 ? 0 : _ref$longitude,
  1896. _ref$zoom = _ref.zoom,
  1897. zoom = _ref$zoom === void 0 ? 0 : _ref$zoom,
  1898. _ref$pitch = _ref.pitch,
  1899. pitch = _ref$pitch === void 0 ? 0 : _ref$pitch,
  1900. _ref$bearing = _ref.bearing,
  1901. bearing = _ref$bearing === void 0 ? 0 : _ref$bearing,
  1902. _ref$altitude = _ref.altitude,
  1903. altitude = _ref$altitude === void 0 ? 1.5 : _ref$altitude,
  1904. nearZMultiplier = _ref.nearZMultiplier,
  1905. farZMultiplier = _ref.farZMultiplier;
  1906.  
  1907. _classCallCheck(this, WebMercatorViewport);
  1908.  
  1909. width = width || 1;
  1910. height = height || 1;
  1911. var scale = zoomToScale$1(zoom);
  1912. altitude = Math.max(0.75, altitude);
  1913. var center = lngLatToWorld([longitude, latitude], scale);
  1914. center[2] = 0;
  1915. var projectionMatrix = getProjectionMatrix({
  1916. width: width,
  1917. height: height,
  1918. pitch: pitch,
  1919. bearing: bearing,
  1920. altitude: altitude,
  1921. nearZMultiplier: nearZMultiplier || 1 / height,
  1922. farZMultiplier: farZMultiplier || 1.01
  1923. });
  1924. var viewMatrix = getViewMatrix({
  1925. height: height,
  1926. center: center,
  1927. pitch: pitch,
  1928. bearing: bearing,
  1929. altitude: altitude,
  1930. flipY: true
  1931. });
  1932. _this = _possibleConstructorReturn(this, _getPrototypeOf(WebMercatorViewport).call(this, {
  1933. width: width,
  1934. height: height,
  1935. viewMatrix: viewMatrix,
  1936. projectionMatrix: projectionMatrix
  1937. }));
  1938. _this.latitude = latitude;
  1939. _this.longitude = longitude;
  1940. _this.zoom = zoom;
  1941. _this.pitch = pitch;
  1942. _this.bearing = bearing;
  1943. _this.altitude = altitude;
  1944. _this.scale = scale;
  1945. _this.center = center;
  1946. _this.pixelsPerMeter = getDistanceScales$1(_assertThisInitialized(_assertThisInitialized(_this))).pixelsPerMeter[2];
  1947. Object.freeze(_assertThisInitialized(_assertThisInitialized(_this)));
  1948. return _this;
  1949. }
  1950.  
  1951. _createClass(WebMercatorViewport, [{
  1952. key: "projectFlat",
  1953. value: function projectFlat(lngLat) {
  1954. var scale = arguments.length > 1 && arguments[1] !== undefined ? arguments[1] : this.scale;
  1955. return lngLatToWorld(lngLat, scale);
  1956. }
  1957. }, {
  1958. key: "unprojectFlat",
  1959. value: function unprojectFlat(xy) {
  1960. var scale = arguments.length > 1 && arguments[1] !== undefined ? arguments[1] : this.scale;
  1961. return worldToLngLat(xy, scale);
  1962. }
  1963. }, {
  1964. key: "getMapCenterByLngLatPosition",
  1965. value: function getMapCenterByLngLatPosition(_ref2) {
  1966. var lngLat = _ref2.lngLat,
  1967. pos = _ref2.pos;
  1968. var fromLocation = pixelsToWorld(pos, this.pixelUnprojectionMatrix);
  1969. var toLocation = lngLatToWorld(lngLat, this.scale);
  1970. var translate = add([], toLocation, negate$1([], fromLocation));
  1971. var newCenter = add([], this.center, translate);
  1972. return worldToLngLat(newCenter, this.scale);
  1973. }
  1974. }, {
  1975. key: "getLocationAtPoint",
  1976. value: function getLocationAtPoint(_ref3) {
  1977. var lngLat = _ref3.lngLat,
  1978. pos = _ref3.pos;
  1979. return this.getMapCenterByLngLatPosition({
  1980. lngLat: lngLat,
  1981. pos: pos
  1982. });
  1983. }
  1984. }, {
  1985. key: "fitBounds",
  1986. value: function fitBounds$1(bounds) {
  1987. var options = arguments.length > 1 && arguments[1] !== undefined ? arguments[1] : {};
  1988. var width = this.width,
  1989. height = this.height;
  1990.  
  1991. var _fitBounds2 = fitBounds(Object.assign({
  1992. width: width,
  1993. height: height,
  1994. bounds: bounds
  1995. }, options)),
  1996. longitude = _fitBounds2.longitude,
  1997. latitude = _fitBounds2.latitude,
  1998. zoom = _fitBounds2.zoom;
  1999.  
  2000. return new WebMercatorViewport({
  2001. width: width,
  2002. height: height,
  2003. longitude: longitude,
  2004. latitude: latitude,
  2005. zoom: zoom
  2006. });
  2007. }
  2008. }]);
  2009.  
  2010. return WebMercatorViewport;
  2011. }(Viewport);
  2012.  
  2013. /**
  2014. * borrow from
  2015. * https://github.com/uber-common/viewport-mercator-project/blob/master/src/web-mercator-utils.js
  2016. */
  2017.  
  2018. const PI = Math.PI;
  2019. const DEGREES_TO_RADIANS = PI / 180;
  2020. // const RADIANS_TO_DEGREES = 180 / PI;
  2021. const TILE_SIZE = 512;
  2022. // Average circumference (40075 km equatorial, 40007 km meridional)
  2023. const EARTH_CIRCUMFERENCE = 40.03e6;
  2024.  
  2025. // Mapbox default altitude
  2026. // const DEFAULT_ALTITUDE = 1.5;
  2027.  
  2028. function zoomToScale(zoom) {
  2029. return Math.pow(2, zoom);
  2030. }
  2031.  
  2032. /**
  2033. * Calculate distance scales in meters around current lat/lon, both for
  2034. * degrees and pixels.
  2035. * In mercator projection mode, the distance scales vary significantly
  2036. * with latitude.
  2037. */
  2038. function getDistanceScales(options) {
  2039. let {
  2040. latitude = 0, zoom = 1, scale, highPrecision = false
  2041. } = options;
  2042.  
  2043. // Calculate scale from zoom if not provided
  2044. scale = scale !== undefined ? scale : zoomToScale(zoom);
  2045.  
  2046. const result = {};
  2047. const worldSize = TILE_SIZE * scale;
  2048. const latCosine = Math.cos(latitude * DEGREES_TO_RADIANS);
  2049.  
  2050. /**
  2051. * Number of pixels occupied by one degree longitude around current lat/lon:
  2052. pixelsPerDegreeX = d(lngLatToWorld([lng, lat])[0])/d(lng)
  2053. = scale * TILE_SIZE * DEGREES_TO_RADIANS / (2 * PI)
  2054. pixelsPerDegreeY = d(lngLatToWorld([lng, lat])[1])/d(lat)
  2055. = -scale * TILE_SIZE * DEGREES_TO_RADIANS / cos(lat * DEGREES_TO_RADIANS) / (2 * PI)
  2056. */
  2057. const pixelsPerDegreeX = worldSize / 360;
  2058. const pixelsPerDegreeY = pixelsPerDegreeX / latCosine;
  2059.  
  2060. /**
  2061. * Number of pixels occupied by one meter around current lat/lon:
  2062. */
  2063. const altPixelsPerMeter = worldSize / EARTH_CIRCUMFERENCE / latCosine;
  2064.  
  2065. /**
  2066. * LngLat: longitude -> east and latitude -> north (bottom left)
  2067. * UTM meter offset: x -> east and y -> north (bottom left)
  2068. * World space: x -> east and y -> south (top left)
  2069. *
  2070. * Y needs to be flipped when converting delta degree/meter to delta pixels
  2071. */
  2072. result.pixelsPerMeter = [altPixelsPerMeter, -altPixelsPerMeter, altPixelsPerMeter];
  2073. result.metersPerPixel = [1 / altPixelsPerMeter, -1 / altPixelsPerMeter, 1 / altPixelsPerMeter];
  2074.  
  2075. result.pixelsPerDegree = [pixelsPerDegreeX, -pixelsPerDegreeY, altPixelsPerMeter];
  2076. result.degreesPerPixel = [1 / pixelsPerDegreeX, -1 / pixelsPerDegreeY, 1 / altPixelsPerMeter];
  2077.  
  2078. /**
  2079. * Taylor series 2nd order for 1/latCosine
  2080. f'(a) * (x - a)
  2081. = d(1/cos(lat * DEGREES_TO_RADIANS))/d(lat) * dLat
  2082. = DEGREES_TO_RADIANS * tan(lat * DEGREES_TO_RADIANS) / cos(lat * DEGREES_TO_RADIANS) * dLat
  2083. */
  2084. if (highPrecision) {
  2085. const latCosine2 = DEGREES_TO_RADIANS * Math.tan(latitude * DEGREES_TO_RADIANS) / latCosine;
  2086. const pixelsPerDegreeY2 = pixelsPerDegreeX * latCosine2 / 2;
  2087.  
  2088. const altPixelsPerDegree2 = worldSize / EARTH_CIRCUMFERENCE * latCosine2;
  2089. const altPixelsPerMeter2 = altPixelsPerDegree2 / pixelsPerDegreeY * altPixelsPerMeter;
  2090.  
  2091. result.pixelsPerDegree2 = [0, -pixelsPerDegreeY2, altPixelsPerDegree2];
  2092. result.pixelsPerMeter2 = [altPixelsPerMeter2, 0, altPixelsPerMeter2];
  2093. }
  2094.  
  2095. // Main results, used for converting meters to latlng deltas and scaling offsets
  2096. return result;
  2097. }
  2098.  
  2099. return class {
  2100.  
  2101. constructor(options) {
  2102. this.id = options.id;
  2103. this.type = "custom";
  2104. this.renderingMode = '2d';
  2105. this.url = options.url;
  2106. if(!!!(options.tileType)){
  2107. let tiles = options.subdomains.map(i => options.url.replaceAll('{s}',i));
  2108. !(tiles.length) && (tiles = [options.url]);
  2109. this.layerParams = {
  2110. source:{"type": "raster", tiles, "tileSize": 256},
  2111. layer:{"type": "raster", "source": options.id, "minzoom": options.minZoom || 0, "maxzoom": options.maxZoom || 18}
  2112. }
  2113. }
  2114.  
  2115. this.options = {
  2116. //服务器编号
  2117. subdomains: null,
  2118. minZoom: 3,
  2119. maxZoom: 18,
  2120. tileType: 'xyz' //bd09,xyz
  2121. };
  2122. setOptions(this, options); //合并属性
  2123.  
  2124. //着色器程序
  2125. this.program;
  2126.  
  2127. //存放当前显示的瓦片
  2128. this.showTiles = [];
  2129.  
  2130. //存放所有加载过的瓦片
  2131. this.tileCache = {};
  2132.  
  2133. //存放瓦片号对应的经纬度
  2134. this.gridCache = {};
  2135.  
  2136. //记录渲染时的变换矩阵。
  2137. //如果瓦片因为网速慢,在渲染完成后才加载过来,可以使用这个矩阵主动更新渲染
  2138. this.matrix;
  2139.  
  2140. this.map;
  2141.  
  2142. //记录当前图层是否在显示
  2143. this.isLayerShow;
  2144.  
  2145. this.transformBaidu = new TransformClassBaidu();
  2146. }
  2147.  
  2148. onAdd(map, gl) {
  2149. this.map = map;
  2150.  
  2151. // 着色器程序参考:https://github.com/xiaoiver/custom-mapbox-layer/blob/master/src/shaders/project.glsl
  2152. var vertexSource = "" + "uniform mat4 u_matrix;" + "attribute vec2 a_pos;" + "attribute vec2 a_TextCoord;" + "varying vec2 v_TextCoord;" + "const float TILE_SIZE = 512.0;" + "const float PI = 3.1415926536;" + "const float WORLD_SCALE = TILE_SIZE / (PI * 2.0);" + "uniform float u_project_scale;" + "uniform bool u_is_offset;" + "uniform vec3 u_pixels_per_degree;" + "uniform vec3 u_pixels_per_degree2;" + "uniform vec3 u_pixels_per_meter;" + "uniform vec2 u_viewport_center;" + "uniform vec4 u_viewport_center_projection;" + "uniform vec2 u_viewport_size;" + "float project_scale(float meters) {" + " return meters * u_pixels_per_meter.z;" + "}" + "vec3 project_scale(vec3 position) {" + " return position * u_pixels_per_meter;" + "}" + "vec2 project_mercator(vec2 lnglat) {" + " float x = lnglat.x;" + " return vec2(" + " radians(x) + PI, PI - log(tan(PI * 0.25 + radians(lnglat.y) * 0.5))" + " );" + "}" + "vec4 project_offset(vec4 offset) {" + " float dy = offset.y;" + " dy = clamp(dy, -1., 1.);" + " vec3 pixels_per_unit = u_pixels_per_degree + u_pixels_per_degree2 * dy;" + " return vec4(offset.xyz * pixels_per_unit, offset.w);" + "}" + "vec4 project_position(vec4 position) {" + " if (u_is_offset) {" + " float X = position.x - u_viewport_center.x;" + " float Y = position.y - u_viewport_center.y;" + " return project_offset(vec4(X, Y, position.z, position.w));" + " }" + " else {" + " return vec4(" + " project_mercator(position.xy) * WORLD_SCALE * u_project_scale, project_scale(position.z), position.w" + " );" + " }" + "}" + "vec4 project_to_clipping_space(vec3 position) {" + " vec4 project_pos = project_position(vec4(position, 1.0));" + " return u_matrix * project_pos + u_viewport_center_projection;" + "}" + "void main() {" + " vec4 project_pos = project_position(vec4(a_pos, 0.0, 1.0));" + " gl_Position = u_matrix * project_pos + u_viewport_center_projection;" + " v_TextCoord = a_TextCoord;" + "}";
  2153.  
  2154. var fragmentSource = "" + "precision mediump float;" + "uniform sampler2D u_Sampler; " + "varying vec2 v_TextCoord; " + "void main() {" + " gl_FragColor = texture2D(u_Sampler, v_TextCoord);" +
  2155. // " gl_FragColor = vec4(1.0, 0.0, 0.0, 0.5);" +
  2156. "}";
  2157.  
  2158. //初始化顶点着色器
  2159. var vertexShader = gl.createShader(gl.VERTEX_SHADER);
  2160. gl.shaderSource(vertexShader, vertexSource);
  2161. gl.compileShader(vertexShader);
  2162. //初始化片元着色器
  2163. var fragmentShader = gl.createShader(gl.FRAGMENT_SHADER);
  2164. gl.shaderSource(fragmentShader, fragmentSource);
  2165. gl.compileShader(fragmentShader);
  2166. //初始化着色器程序
  2167. this.program = gl.createProgram();
  2168. gl.attachShader(this.program, vertexShader);
  2169. gl.attachShader(this.program, fragmentShader);
  2170. gl.linkProgram(this.program);
  2171.  
  2172. //获取顶点位置变量
  2173. this.a_Pos = gl.getAttribLocation(this.program, "a_pos");
  2174. this.a_TextCoord = gl.getAttribLocation(this.program, 'a_TextCoord');
  2175.  
  2176. this.isLayerShow = true;
  2177. map.on('move', () => {
  2178. if (this.isLayerShow) this.update(gl, map);
  2179. });
  2180. this.update(gl, map);
  2181. }
  2182.  
  2183. update(gl, map) {
  2184. var center = map.getCenter();
  2185. var zoom;
  2186. var bounds = map.getBounds();
  2187.  
  2188. var minTile, maxTile;
  2189. if (this.options.tileType === 'xyz') {
  2190. zoom = parseInt(map.getZoom() + 1.4); //解决瓦片上文字偏大的问题
  2191. //把当前显示范围做偏移,后面加载瓦片时会再偏移回来
  2192. //如果不这样做的话,大比例尺时,瓦片偏移后,屏幕边缘会有空白区域
  2193. var northWest = gcj02_To_gps84(bounds.getNorthWest());
  2194. var southEast = gcj02_To_gps84(bounds.getSouthEast());
  2195. //算出当前范围的瓦片编号
  2196. minTile = lonLatToTileNumbers(northWest.lng, northWest.lat, zoom);
  2197. maxTile = lonLatToTileNumbers(southEast.lng, southEast.lat, zoom);
  2198. } else if (this.options.tileType === 'bd09') {
  2199. zoom = parseInt(map.getZoom() + 1.8); //解决瓦片上文字偏大的问题
  2200. var southWest = gps84_To_bd09(bounds.getSouthWest());
  2201. var northEast = gps84_To_bd09(bounds.getNorthEast());
  2202. minTile = this.transformBaidu.lnglatToTile(southWest.lng, southWest.lat, zoom);
  2203. maxTile = this.transformBaidu.lnglatToTile(northEast.lng, northEast.lat, zoom);
  2204. }
  2205. var currentTiles = [];
  2206. for (var x = minTile[0]; x <= maxTile[0]; x++) {
  2207. for (var y = minTile[1]; y <= maxTile[1]; y++) {
  2208. var xyz = {
  2209. x: x,
  2210. y: y,
  2211. z: zoom
  2212. };
  2213. currentTiles.push(xyz);
  2214.  
  2215. //把瓦片号对应的经纬度缓存起来,
  2216. //存起来是因为贴纹理时需要瓦片4个角的经纬度,这样可以避免重复计算
  2217. //行和列向外多计算一个瓦片数,这样保证瓦片4个角都有经纬度可以取到
  2218. this.addGridCache(xyz, 0, 0);
  2219. if (x === maxTile[0]) this.addGridCache(xyz, 1, 0);
  2220. if (y === maxTile[1]) this.addGridCache(xyz, 0, 1);
  2221. if (x === maxTile[0] && y === maxTile[1]) this.addGridCache(xyz, 1, 1);
  2222. }
  2223. }
  2224.  
  2225. //瓦片设置为从中间向周边的排序
  2226. if (this.options.tileType === 'xyz') var centerTile = lonLatToTileNumbers(center.lng, center.lat, zoom); //计算中心点所在的瓦片号
  2227. else if (this.options.tileType === 'bd09') centerTile = this.transformBaidu.lnglatToTile(center.lng, center.lat, zoom);
  2228. currentTiles.sort((a, b) => {
  2229. return this.tileDistance(a, centerTile) - this.tileDistance(b, centerTile);
  2230. });
  2231.  
  2232. //加载瓦片
  2233. this.showTiles = [];
  2234. for (var xyz of currentTiles) {
  2235. //走缓存或新加载
  2236. if (this.tileCache[this.createTileKey(xyz)]) {
  2237. this.showTiles.push(this.tileCache[this.createTileKey(xyz)]);
  2238. } else {
  2239. var tile = this.createTile(gl, xyz);
  2240. this.showTiles.push(tile);
  2241. this.tileCache[this.createTileKey(xyz)] = tile;
  2242. }
  2243. }
  2244. }
  2245.  
  2246. //缓存瓦片号对应的经纬度
  2247. addGridCache(xyz, xPlus, yPlus) {
  2248. var key = this.createTileKey(xyz.x + xPlus, xyz.y + yPlus, xyz.z);
  2249. if (!this.gridCache[key]) {
  2250. if (this.options.tileType === 'xyz') this.gridCache[key] = gps84_To_gcj02(tileNumbersToLonLat(xyz.x + xPlus, xyz.y + yPlus, xyz.z));else if (this.options.tileType === 'bd09') this.gridCache[key] = bd09_To_gps84(this.transformBaidu.pixelToLnglat(0, 0, xyz.x + xPlus, xyz.y + yPlus, xyz.z));
  2251. }
  2252. }
  2253.  
  2254. //计算两个瓦片编号的距离
  2255. tileDistance(tile1, tile2) {
  2256. //计算直角三角形斜边长度,c(斜边)=√(a²+b²)。(a,b为两直角边)
  2257. return Math.sqrt(Math.pow(tile1.x - tile2[0], 2) + Math.pow(tile1.y - tile2[1], 2));
  2258. }
  2259.  
  2260. //创建瓦片id
  2261. createTileKey(xyz, y, z) {
  2262. if (xyz instanceof Object) {
  2263. return xyz.z + '/' + xyz.x + '/' + xyz.y;
  2264. } else {
  2265. var x = xyz;
  2266. return z + '/' + x + '/' + y;
  2267. }
  2268. }
  2269.  
  2270. //创建瓦片
  2271. createTile(gl, xyz) {
  2272. //替换请求地址中的变量
  2273. var _url = template(this.url, {
  2274. s: this.options.subdomains[Math.abs(xyz.x + xyz.y) % this.options.subdomains.length],
  2275. x: xyz.x,
  2276. y: xyz.y,
  2277. z: xyz.z
  2278. });
  2279.  
  2280. var tile = {
  2281. xyz: xyz
  2282. };
  2283.  
  2284. //瓦片编号转经纬度,并进行偏移
  2285. var leftTop, rightTop, leftBottom, rightBottom;
  2286. if (this.options.tileType === 'xyz') {
  2287. leftTop = this.gridCache[this.createTileKey(xyz)];
  2288. rightTop = this.gridCache[this.createTileKey(xyz.x + 1, xyz.y, xyz.z)];
  2289. leftBottom = this.gridCache[this.createTileKey(xyz.x, xyz.y + 1, xyz.z)];
  2290. rightBottom = this.gridCache[this.createTileKey(xyz.x + 1, xyz.y + 1, xyz.z)];
  2291. } else if (this.options.tileType === 'bd09') {
  2292. leftTop = this.gridCache[this.createTileKey(xyz.x, xyz.y + 1, xyz.z)];
  2293. rightTop = this.gridCache[this.createTileKey(xyz.x + 1, xyz.y + 1, xyz.z)];
  2294. leftBottom = this.gridCache[this.createTileKey(xyz)];
  2295. rightBottom = this.gridCache[this.createTileKey(xyz.x + 1, xyz.y, xyz.z)];
  2296. }
  2297.  
  2298. //顶点坐标+纹理坐标
  2299. var attrData = new Float32Array([leftTop.lng, leftTop.lat, 0.0, 1.0, leftBottom.lng, leftBottom.lat, 0.0, 0.0, rightTop.lng, rightTop.lat, 1.0, 1.0, rightBottom.lng, rightBottom.lat, 1.0, 0.0]);
  2300. // var attrData = new Float32Array([
  2301. // 116.38967958133532, 39.90811009556515, 0.0, 1.0,
  2302. // 116.38967958133532, 39.90294980726742, 0.0, 0.0,
  2303. // 116.39486013141436, 39.90811009556515, 1.0, 1.0,
  2304. // 116.39486013141436, 39.90294980726742, 1.0, 0.0
  2305. // ])
  2306. var FSIZE = attrData.BYTES_PER_ELEMENT;
  2307. //创建缓冲区并传入数据
  2308. var buffer = gl.createBuffer();
  2309. gl.bindBuffer(gl.ARRAY_BUFFER, buffer);
  2310. gl.bufferData(gl.ARRAY_BUFFER, attrData, gl.STATIC_DRAW);
  2311. tile.buffer = buffer;
  2312. //从缓冲区中获取顶点数据的参数
  2313. tile.PosParam = {
  2314. size: 2,
  2315. stride: FSIZE * 4,
  2316. offset: 0
  2317. //从缓冲区中获取纹理数据的参数
  2318. };tile.TextCoordParam = {
  2319. size: 2,
  2320. stride: FSIZE * 4,
  2321. offset: FSIZE * 2
  2322.  
  2323. //加载瓦片
  2324. };var img = new Image();
  2325. img.onload = () => {
  2326. // 创建纹理对象
  2327. tile.texture = gl.createTexture();
  2328. //向target绑定纹理对象
  2329. gl.bindTexture(gl.TEXTURE_2D, tile.texture);
  2330. //对纹理进行Y轴反转
  2331. gl.pixelStorei(gl.UNPACK_FLIP_Y_WEBGL, 1);
  2332. //配置纹理图像
  2333. gl.texImage2D(gl.TEXTURE_2D, 0, gl.RGBA, gl.RGBA, gl.UNSIGNED_BYTE, img);
  2334.  
  2335. tile.isLoad = true;
  2336.  
  2337. this.map.triggerRepaint(); //主动让地图重绘
  2338. };
  2339. img.crossOrigin = true;
  2340. img.src = _url;
  2341.  
  2342. return tile;
  2343. }
  2344.  
  2345. //渲染
  2346. render(gl, matrix) {
  2347.  
  2348. if (this.map.getZoom() < this.options.minZoom || this.map.getZoom() > this.options.maxZoom) return;
  2349.  
  2350. //记录变换矩阵,用于瓦片加载后主动绘制
  2351. this.matrix = matrix;
  2352.  
  2353. //应用着色程序
  2354. //必须写到这里,不能写到onAdd中,不然gl中的着色程序可能不是上面写的,会导致下面的变量获取不到
  2355. gl.useProgram(this.program);
  2356.  
  2357. for (var tile of this.showTiles) {
  2358. if (!tile.isLoad) continue;
  2359.  
  2360. //向target绑定纹理对象
  2361. gl.bindTexture(gl.TEXTURE_2D, tile.texture);
  2362. //开启0号纹理单元
  2363. gl.activeTexture(gl.TEXTURE0);
  2364. //配置纹理参数
  2365. gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_MIN_FILTER, gl.LINEAR);
  2366. gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_WRAP_S, gl.CLAMP_TO_EDGE);
  2367. gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_WRAP_T, gl.MIRRORED_REPEAT);
  2368. // 获取纹理的存储位置
  2369. var u_Sampler = gl.getUniformLocation(this.program, 'u_Sampler');
  2370. //将0号纹理传递给着色器
  2371. gl.uniform1i(u_Sampler, 0);
  2372.  
  2373. gl.bindBuffer(gl.ARRAY_BUFFER, tile.buffer);
  2374. //设置从缓冲区获取顶点数据的规则
  2375. gl.vertexAttribPointer(this.a_Pos, tile.PosParam.size, gl.FLOAT, false, tile.PosParam.stride, tile.PosParam.offset);
  2376. gl.vertexAttribPointer(this.a_TextCoord, tile.TextCoordParam.size, gl.FLOAT, false, tile.TextCoordParam.stride, tile.TextCoordParam.offset);
  2377. //激活顶点数据缓冲区
  2378. gl.enableVertexAttribArray(this.a_Pos);
  2379. gl.enableVertexAttribArray(this.a_TextCoord);
  2380.  
  2381. // 设置位置的顶点参数
  2382. this.setVertex(gl);
  2383.  
  2384. //开启阿尔法混合,实现注记半透明效果
  2385. gl.enable(gl.BLEND);
  2386. gl.blendFunc(gl.SRC_ALPHA, gl.ONE_MINUS_SRC_ALPHA);
  2387.  
  2388. //绘制图形
  2389. gl.drawArrays(gl.TRIANGLE_STRIP, 0, 4);
  2390. }
  2391. }
  2392.  
  2393. // 设置位置的顶点参数
  2394. //参考:https://github.com/xiaoiver/custom-mapbox-layer/blob/master/src/layers/PointCloudLayer2.ts
  2395. setVertex(gl) {
  2396. const currentZoomLevel = this.map.getZoom();
  2397. const bearing = this.map.getBearing();
  2398. const pitch = this.map.getPitch();
  2399. const center = this.map.getCenter();
  2400.  
  2401. const viewport = new WebMercatorViewport({
  2402. // width: gl.drawingBufferWidth*1.11,
  2403. // height: gl.drawingBufferHeight*1.11,
  2404. width: gl.drawingBufferWidth,
  2405. height: gl.drawingBufferHeight,
  2406.  
  2407. longitude: center.lng,
  2408. latitude: center.lat,
  2409. zoom: currentZoomLevel,
  2410. pitch,
  2411. bearing
  2412. });
  2413.  
  2414. // @ts-ignore
  2415. const { viewProjectionMatrix, projectionMatrix, viewMatrix, viewMatrixUncentered } = viewport;
  2416.  
  2417. let drawParams = {
  2418. // @ts-ignore
  2419. 'u_matrix': viewProjectionMatrix,
  2420. 'u_point_size': this.pointSize,
  2421. 'u_is_offset': false,
  2422. 'u_pixels_per_degree': [0, 0, 0],
  2423. 'u_pixels_per_degree2': [0, 0, 0],
  2424. 'u_viewport_center': [0, 0],
  2425. 'u_pixels_per_meter': [0, 0, 0],
  2426. 'u_project_scale': zoomToScale(currentZoomLevel),
  2427. 'u_viewport_center_projection': [0, 0, 0, 0]
  2428. };
  2429.  
  2430. if (currentZoomLevel > 12) {
  2431. const { pixelsPerDegree, pixelsPerDegree2 } = getDistanceScales({
  2432. longitude: center.lng,
  2433. latitude: center.lat,
  2434. zoom: currentZoomLevel,
  2435. highPrecision: true
  2436. });
  2437.  
  2438. const positionPixels = viewport.projectFlat([Math.fround(center.lng), Math.fround(center.lat)], Math.pow(2, currentZoomLevel));
  2439.  
  2440. const projectionCenter = transformMat4([], [positionPixels[0], positionPixels[1], 0.0, 1.0], viewProjectionMatrix);
  2441.  
  2442. // Always apply uncentered projection matrix if available (shader adds center)
  2443. let viewMatrix2 = viewMatrixUncentered || viewMatrix;
  2444.  
  2445. // Zero out 4th coordinate ("after" model matrix) - avoids further translations
  2446. // viewMatrix = new Matrix4(viewMatrixUncentered || viewMatrix)
  2447. // .multiplyRight(VECTOR_TO_POINT_MATRIX);
  2448. let viewProjectionMatrix2 = multiply([], projectionMatrix, viewMatrix2);
  2449. const VECTOR_TO_POINT_MATRIX = [1, 0, 0, 0, 0, 1, 0, 0, 0, 0, 1, 0, 0, 0, 0, 0];
  2450. viewProjectionMatrix2 = multiply([], viewProjectionMatrix2, VECTOR_TO_POINT_MATRIX);
  2451.  
  2452. drawParams['u_matrix'] = viewProjectionMatrix2;
  2453. drawParams['u_is_offset'] = true;
  2454. drawParams['u_viewport_center'] = [Math.fround(center.lng), Math.fround(center.lat)];
  2455. // @ts-ignore
  2456. drawParams['u_viewport_center_projection'] = projectionCenter;
  2457. drawParams['u_pixels_per_degree'] = pixelsPerDegree && pixelsPerDegree.map(p => Math.fround(p));
  2458. drawParams['u_pixels_per_degree2'] = pixelsPerDegree2 && pixelsPerDegree2.map(p => Math.fround(p));
  2459. }
  2460.  
  2461. gl.uniformMatrix4fv(gl.getUniformLocation(this.program, "u_matrix"), false, drawParams['u_matrix']);
  2462.  
  2463. gl.uniform1f(gl.getUniformLocation(this.program, "u_project_scale"), drawParams['u_project_scale']);
  2464. gl.uniform1i(gl.getUniformLocation(this.program, "u_is_offset"), drawParams['u_is_offset'] ? 1 : 0);
  2465. gl.uniform3fv(gl.getUniformLocation(this.program, "u_pixels_per_degree"), drawParams['u_pixels_per_degree']);
  2466. gl.uniform3fv(gl.getUniformLocation(this.program, "u_pixels_per_degree2"), drawParams['u_pixels_per_degree2']);
  2467. gl.uniform3fv(gl.getUniformLocation(this.program, "u_pixels_per_meter"), drawParams['u_pixels_per_meter']);
  2468. gl.uniform2fv(gl.getUniformLocation(this.program, "u_viewport_center"), drawParams['u_viewport_center']);
  2469. gl.uniform4fv(gl.getUniformLocation(this.program, "u_viewport_center_projection"), drawParams['u_viewport_center_projection']);
  2470. }
  2471.  
  2472. //当map移除当前图层时调用
  2473. onRemove(map, gl) {
  2474. this.isLayerShow = false;
  2475. }
  2476.  
  2477. addTo(map){
  2478. this.map = map;
  2479. if(!this.layerParams) return map.addLayer(this);
  2480. this.map.addSource(this.id,this.layerParams.source);
  2481. this.map.addLayer({id:this.id,...this.layerParams.layer});
  2482. }
  2483.  
  2484. remove(map, gl) {
  2485. if(!this.map) return console.warn(`Please trigger "addTo" This method is called after the "map" instance is passed in;`);
  2486. let layer = this.map.getLayer(this.id);
  2487. if(!layer) return console.warn(`The current layer has not been added to the map;`);
  2488. this.map.removeLayer(this.id);
  2489. }
  2490.  
  2491. hide(){
  2492. this.isLayerShow = false;
  2493. this.map.setLayoutProperty(this.id, 'visibility', 'none');
  2494. }
  2495.  
  2496. show(){
  2497. this.isLayerShow = true;
  2498. this.map.setLayoutProperty(this.id, 'visibility', 'visible');
  2499. }
  2500. }
  2501. })));