@superrouteca/smap 1.1.7 → 1.2.1

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
package/dist/smap.js CHANGED
@@ -1,4 +1,4 @@
1
- /*! sMap Web SDK 1.1.7. Bundles maplibre-gl 6.16.0 (BSD-3-Clause), see vendor-licenses.txt. */
1
+ /*! sMap Web SDK 1.2.1. Bundles maplibre-gl 6.16.0 (BSD-3-Clause), see vendor-licenses.txt. */
2
2
  (function () {
3
3
  function smapCreateEngine() {
4
4
  var SMAP_BASE_URL = (typeof document !== 'undefined' && document.baseURI) || (typeof location !== 'undefined' && location.href) || 'about:blank';
@@ -28280,6 +28280,131 @@ function smapCreateInterop() {
28280
28280
  return json;
28281
28281
  }
28282
28282
 
28283
+ // ------------------------------------------------------------------ geometry helpers (G14)
28284
+
28285
+ var EARTH_RADIUS = 6371008.8;
28286
+ function rad(d) { return d * Math.PI / 180; }
28287
+ function lngLatOf(v) {
28288
+ if (Array.isArray(v)) { return [+v[0], +v[1]]; }
28289
+ if (v && typeof v === 'object') {
28290
+ if (v.type === 'Feature') { return lngLatOf(v.geometry); }
28291
+ if (v.type === 'Point') { return lngLatOf(v.coordinates); }
28292
+ return [+(v.lng !== undefined ? v.lng : v.lon), +v.lat];
28293
+ }
28294
+ throw new Error('sMap: not a position');
28295
+ }
28296
+ function geometryOf(v) { return v && v.type === 'Feature' ? v.geometry : v; }
28297
+
28298
+ /** Great-circle distance in metres between two positions ([lng, lat], {lng, lat} or a Point). */
28299
+ function distance(a, b) {
28300
+ var p = lngLatOf(a), q = lngLatOf(b);
28301
+ var dLat = rad(q[1] - p[1]), dLng = rad(q[0] - p[0]);
28302
+ var h = Math.sin(dLat / 2) * Math.sin(dLat / 2) + Math.cos(rad(p[1])) * Math.cos(rad(q[1])) * Math.sin(dLng / 2) * Math.sin(dLng / 2);
28303
+ return 2 * EARTH_RADIUS * Math.asin(Math.min(1, Math.sqrt(h)));
28304
+ }
28305
+
28306
+ function lineCoords(line) {
28307
+ var g = geometryOf(line);
28308
+ if (Array.isArray(g)) { return g.map(lngLatOf); }
28309
+ if (g && g.type === 'LineString') { return g.coordinates; }
28310
+ throw new Error('sMap: not a line');
28311
+ }
28312
+
28313
+ /** Length in metres of a line ([[lng, lat], …], a LineString or its Feature). */
28314
+ function length(line) {
28315
+ var c = lineCoords(line), total = 0;
28316
+ for (var i = 1; i < c.length; i++) { total += distance(c[i - 1], c[i]); }
28317
+ return total;
28318
+ }
28319
+
28320
+ /** [[west, south], [east, north]] of any GeoJSON (or null when it holds no position). */
28321
+ function bounds(geojson) {
28322
+ var b = null;
28323
+ (function walk(v) {
28324
+ if (!v) { return; }
28325
+ if (Array.isArray(v)) {
28326
+ if (typeof v[0] === 'number') {
28327
+ if (!b) { b = [[v[0], v[1]], [v[0], v[1]]]; return; }
28328
+ b[0][0] = Math.min(b[0][0], v[0]); b[0][1] = Math.min(b[0][1], v[1]);
28329
+ b[1][0] = Math.max(b[1][0], v[0]); b[1][1] = Math.max(b[1][1], v[1]);
28330
+ return;
28331
+ }
28332
+ v.forEach(walk);
28333
+ return;
28334
+ }
28335
+ if (v.type === 'FeatureCollection') { (v.features || []).forEach(walk); return; }
28336
+ if (v.type === 'Feature') { walk(v.geometry); return; }
28337
+ if (v.type === 'GeometryCollection') { (v.geometries || []).forEach(walk); return; }
28338
+ walk(v.coordinates);
28339
+ })(geojson);
28340
+ return b;
28341
+ }
28342
+
28343
+ function inRing(p, ring) {
28344
+ var inside = false;
28345
+ for (var i = 0, j = ring.length - 1; i < ring.length; j = i++) {
28346
+ var xi = ring[i][0], yi = ring[i][1], xj = ring[j][0], yj = ring[j][1];
28347
+ if ((yi > p[1]) !== (yj > p[1]) && p[0] < (xj - xi) * (p[1] - yi) / (yj - yi) + xi) { inside = !inside; }
28348
+ }
28349
+ return inside;
28350
+ }
28351
+
28352
+ /** Whether a position is inside a Polygon or MultiPolygon (holes excluded), a Feature of one, or a ring of positions. */
28353
+ function pointInPolygon(point, polygon) {
28354
+ var p = lngLatOf(point), g = geometryOf(polygon);
28355
+ var polys = Array.isArray(g) ? [[g.map(lngLatOf)]] : (g && g.type === 'Polygon' ? [g.coordinates] : (g && g.type === 'MultiPolygon' ? g.coordinates : null));
28356
+ if (!polys) { throw new Error('sMap: not a polygon'); }
28357
+ return polys.some(function (rings) {
28358
+ if (!rings.length || !inRing(p, rings[0])) { return false; }
28359
+ for (var k = 1; k < rings.length; k++) { if (inRing(p, rings[k])) { return false; } }
28360
+ return true;
28361
+ });
28362
+ }
28363
+
28364
+ /**
28365
+ * The point of a line nearest to a position: { point: [lng, lat], distance (metres from the position), index (of the
28366
+ * segment's first vertex), along (metres from the line's start) }. Measured in a local flat projection around the
28367
+ * position, which is exact to well under a metre for the distances a map shows.
28368
+ */
28369
+ function nearestPointOnLine(line, point) {
28370
+ var c = lineCoords(line), p = lngLatOf(point);
28371
+ if (!c.length) { return null; }
28372
+ var kx = Math.cos(rad(p[1])) * rad(1) * EARTH_RADIUS, ky = rad(1) * EARTH_RADIUS;
28373
+ var best = null, walked = 0;
28374
+ for (var i = 0; i < Math.max(1, c.length - 1); i++) {
28375
+ var a = c[i], b = c[Math.min(i + 1, c.length - 1)];
28376
+ var ax = (a[0] - p[0]) * kx, ay = (a[1] - p[1]) * ky, bx = (b[0] - p[0]) * kx, by = (b[1] - p[1]) * ky;
28377
+ var dx = bx - ax, dy = by - ay, len2 = dx * dx + dy * dy;
28378
+ var t = len2 ? Math.max(0, Math.min(1, -(ax * dx + ay * dy) / len2)) : 0;
28379
+ var x = ax + t * dx, y = ay + t * dy, d = Math.sqrt(x * x + y * y);
28380
+ var seg = distance(a, b);
28381
+ if (!best || d < best.distance) {
28382
+ best = { point: [p[0] + x / kx, p[1] + y / ky], distance: d, index: i, along: walked + seg * t };
28383
+ }
28384
+ walked += seg;
28385
+ }
28386
+ return best;
28387
+ }
28388
+
28389
+ /** Metres from a position to the nearest point of a line. */
28390
+ function distanceToLine(line, point) { var n = nearestPointOnLine(line, point); return n ? n.distance : Infinity; }
28391
+
28392
+ var geo = {
28393
+ distance: distance, length: length, bounds: bounds, pointInPolygon: pointInPolygon,
28394
+ nearestPointOnLine: nearestPointOnLine, distanceToLine: distanceToLine,
28395
+ decodePolyline: function (str, precision) { return decodePolyline(str, precision); },
28396
+ encodePolyline: function (coords, precision) { return encodePolyline(coords, precision); },
28397
+ };
28398
+
28399
+ // three.js for 3D models (G12), handed over once by the page (never bundled, like deck.gl).
28400
+ var three = null;
28401
+ function useThree(THREE, GLTFLoader) {
28402
+ if (!THREE || !THREE.Scene || typeof GLTFLoader !== 'function') { throw new Error('sMap: useThree(THREE, GLTFLoader) takes three.js and its GLTFLoader'); }
28403
+ three = { THREE: THREE, GLTFLoader: GLTFLoader };
28404
+ return three;
28405
+ }
28406
+ function getThree() { return three; }
28407
+
28283
28408
  return {
28284
28409
  DEFAULT_BASE: DEFAULT_BASE,
28285
28410
  SLOTS: SLOTS,
@@ -28302,6 +28427,9 @@ function smapCreateInterop() {
28302
28427
  encodePolyline: encodePolyline,
28303
28428
  },
28304
28429
  convert: convert,
28430
+ geo: geo,
28431
+ useThree: useThree,
28432
+ getThree: getThree,
28305
28433
  styleUrl: styleUrl,
28306
28434
  rasterUrl: rasterUrl,
28307
28435
  rasterTileJsonUrl: rasterTileJsonUrl,
@@ -28325,6 +28453,1342 @@ function smapCreateInterop() {
28325
28453
 
28326
28454
  return module.exports;
28327
28455
  }
28456
+ function smapCreateCanvas() {
28457
+ var module = { exports: {} };
28458
+ var exports = module.exports;
28459
+ var define;
28460
+ var self = {};
28461
+ // sMap canvas renderer (M67): the map drawn on a 2D canvas for browsers without WebGL 2. It answers the part of the
28462
+ // rendering engine's map interface the Web SDK uses — camera, events, sources, layers of the kinds the SDK makes
28463
+ // (raster, fill, line, circle, symbol, heatmap), hit tests, controls and popups — so the SDK's calls work unchanged.
28464
+ // The street map comes as raster tiles. What needs WebGL (3D buildings, terrain, tilting, turning, custom 3D layers,
28465
+ // hillshade) is left out and named in an 'smap.unsupported' event.
28466
+ (function (root, factory) {
28467
+ if (typeof module === 'object' && module.exports) { module.exports = factory(); } else { root.smapCanvas = factory(); }
28468
+ })(typeof self !== 'undefined' ? self : this, function () {
28469
+ 'use strict';
28470
+
28471
+ var TILE = 512; // world size per zoom level, as the engine counts zoom (512 px tiles)
28472
+ var MAX_LAT = 85.051129;
28473
+ var raf = typeof requestAnimationFrame === 'function' ? requestAnimationFrame.bind(typeof window !== 'undefined' ? window : this) : function (fn) { return setTimeout(function () { fn(Date.now()); }, 16); };
28474
+
28475
+ // ------------------------------------------------------------------ geometry
28476
+
28477
+ function clampLat(lat) { return Math.max(-MAX_LAT, Math.min(MAX_LAT, lat)); }
28478
+ function lngX(lng, scale) { return (lng + 180) / 360 * scale; }
28479
+ function latY(lat, scale) { var s = Math.sin(clampLat(lat) * Math.PI / 180); return (0.5 - Math.log((1 + s) / (1 - s)) / (4 * Math.PI)) * scale; }
28480
+ function xLng(x, scale) { return x / scale * 360 - 180; }
28481
+ function yLat(y, scale) { var n = Math.PI - 2 * Math.PI * y / scale; return 180 / Math.PI * Math.atan(0.5 * (Math.exp(n) - Math.exp(-n))); }
28482
+ function toLngLat(v) {
28483
+ if (Array.isArray(v)) { return { lng: +v[0], lat: +v[1] }; }
28484
+ if (v && v.lng !== undefined) { return { lng: +v.lng, lat: +v.lat }; }
28485
+ if (v && v.lon !== undefined) { return { lng: +v.lon, lat: +v.lat }; }
28486
+ return { lng: 0, lat: 0 };
28487
+ }
28488
+
28489
+ function LngLat(lng, lat) { this.lng = lng; this.lat = lat; }
28490
+ LngLat.prototype.toArray = function () { return [this.lng, this.lat]; };
28491
+
28492
+ function LngLatBounds(sw, ne) {
28493
+ this._sw = null; this._ne = null;
28494
+ if (sw) { this.extend(sw); }
28495
+ if (ne) { this.extend(ne); }
28496
+ }
28497
+ LngLatBounds.prototype.extend = function (v) {
28498
+ if (v instanceof LngLatBounds) { if (v._sw) { this.extend(v._sw); this.extend(v._ne); } return this; }
28499
+ if (Array.isArray(v) && Array.isArray(v[0])) { this.extend(v[0]); this.extend(v[1]); return this; }
28500
+ var p = toLngLat(v);
28501
+ if (!this._sw) { this._sw = new LngLat(p.lng, p.lat); this._ne = new LngLat(p.lng, p.lat); return this; }
28502
+ this._sw.lng = Math.min(this._sw.lng, p.lng); this._sw.lat = Math.min(this._sw.lat, p.lat);
28503
+ this._ne.lng = Math.max(this._ne.lng, p.lng); this._ne.lat = Math.max(this._ne.lat, p.lat);
28504
+ return this;
28505
+ };
28506
+ LngLatBounds.prototype.getWest = function () { return this._sw.lng; };
28507
+ LngLatBounds.prototype.getSouth = function () { return this._sw.lat; };
28508
+ LngLatBounds.prototype.getEast = function () { return this._ne.lng; };
28509
+ LngLatBounds.prototype.getNorth = function () { return this._ne.lat; };
28510
+ LngLatBounds.prototype.getSouthWest = function () { return this._sw; };
28511
+ LngLatBounds.prototype.getNorthEast = function () { return this._ne; };
28512
+ LngLatBounds.prototype.getCenter = function () { return new LngLat((this._sw.lng + this._ne.lng) / 2, (this._sw.lat + this._ne.lat) / 2); };
28513
+ LngLatBounds.prototype.toArray = function () { return [[this._sw.lng, this._sw.lat], [this._ne.lng, this._ne.lat]]; };
28514
+ LngLatBounds.prototype.isEmpty = function () { return !this._sw; };
28515
+
28516
+ function segDist(px, py, ax, ay, bx, by) {
28517
+ var dx = bx - ax, dy = by - ay, l2 = dx * dx + dy * dy;
28518
+ var t = l2 ? Math.max(0, Math.min(1, ((px - ax) * dx + (py - ay) * dy) / l2)) : 0;
28519
+ var x = ax + t * dx - px, y = ay + t * dy - py;
28520
+ return Math.sqrt(x * x + y * y);
28521
+ }
28522
+ function inRing(x, y, ring) {
28523
+ var inside = false;
28524
+ for (var i = 0, j = ring.length - 1; i < ring.length; j = i++) {
28525
+ var xi = ring[i][0], yi = ring[i][1], xj = ring[j][0], yj = ring[j][1];
28526
+ if ((yi > y) !== (yj > y) && x < (xj - xi) * (y - yi) / (yj - yi) + xi) { inside = !inside; }
28527
+ }
28528
+ return inside;
28529
+ }
28530
+
28531
+ // ------------------------------------------------------------------ expressions (the Style Specification subset the SDK writes)
28532
+
28533
+ function typeName(g) { if (!g) { return null; } var t = g.type; return t === 'MultiPoint' ? 'Point' : (t === 'MultiLineString' ? 'LineString' : (t === 'MultiPolygon' ? 'Polygon' : t)); }
28534
+
28535
+ function parseColor(c) { return c; }
28536
+
28537
+ function evaluate(e, ctx) {
28538
+ if (!Array.isArray(e)) { return e; }
28539
+ var op = e[0], p = (ctx.f && ctx.f.properties) || {};
28540
+ var ev = function (x) { return evaluate(x, ctx); };
28541
+ switch (op) {
28542
+ case 'literal': return e[1];
28543
+ case 'get': return e.length > 2 ? (ev(e[2]) || {})[ev(e[1])] : p[ev(e[1])];
28544
+ case 'has': return Object.prototype.hasOwnProperty.call(p, ev(e[1])) && p[ev(e[1])] !== undefined;
28545
+ case '!': return !ev(e[1]);
28546
+ case '==': return ev(e[1]) === ev(e[2]);
28547
+ case '!=': return ev(e[1]) !== ev(e[2]);
28548
+ case '>': return ev(e[1]) > ev(e[2]);
28549
+ case '>=': return ev(e[1]) >= ev(e[2]);
28550
+ case '<': return ev(e[1]) < ev(e[2]);
28551
+ case '<=': return ev(e[1]) <= ev(e[2]);
28552
+ case 'all': for (var a = 1; a < e.length; a++) { if (!ev(e[a])) { return false; } } return true;
28553
+ case 'any': for (var b = 1; b < e.length; b++) { if (ev(e[b])) { return true; } } return false;
28554
+ case 'case':
28555
+ for (var c = 1; c < e.length - 1; c += 2) { if (ev(e[c])) { return ev(e[c + 1]); } }
28556
+ return ev(e[e.length - 1]);
28557
+ case 'match': {
28558
+ var v = ev(e[1]);
28559
+ for (var d = 2; d < e.length - 1; d += 2) {
28560
+ var lab = e[d];
28561
+ if (Array.isArray(lab) ? lab.indexOf(v) >= 0 : lab === v) { return ev(e[d + 1]); }
28562
+ }
28563
+ return ev(e[e.length - 1]);
28564
+ }
28565
+ case 'coalesce': for (var k = 1; k < e.length; k++) { var x = ev(e[k]); if (x !== null && x !== undefined) { return x; } } return null;
28566
+ case 'to-string': { var s = ev(e[1]); return s === null || s === undefined ? '' : String(s); }
28567
+ case 'to-number': {
28568
+ for (var n = 1; n < e.length; n++) { var num = Number(ev(e[n])); if (!isNaN(num) && ev(e[n]) !== null && ev(e[n]) !== '') { return num; } }
28569
+ return 0;
28570
+ }
28571
+ case 'to-color': for (var q = 1; q < e.length; q++) { var col = ev(e[q]); if (typeof col === 'string' && col) { return col; } } return '#000000';
28572
+ case 'concat': { var out = ''; for (var r = 1; r < e.length; r++) { var part = ev(e[r]); out += part === null || part === undefined ? '' : String(part); } return out; }
28573
+ case 'zoom': return ctx.zoom;
28574
+ case 'heatmap-density': return ctx.density || 0;
28575
+ case 'geometry-type': return typeName(ctx.f && ctx.f.geometry);
28576
+ case 'id': return ctx.f ? ctx.f.id : null;
28577
+ case 'step': {
28578
+ var input = ev(e[1]), val = ev(e[2]);
28579
+ for (var st = 3; st < e.length; st += 2) { if (input >= e[st]) { val = ev(e[st + 1]); } else { break; } }
28580
+ return val;
28581
+ }
28582
+ case 'interpolate': {
28583
+ var at = ev(e[2]), stops = e.slice(3);
28584
+ if (at <= stops[0]) { return ev(stops[1]); }
28585
+ for (var i = 2; i < stops.length; i += 2) {
28586
+ if (at <= stops[i]) {
28587
+ var lo = ev(stops[i - 1]), hi = ev(stops[i]), t = (at - stops[i - 2]) / (stops[i] - stops[i - 2]);
28588
+ hi = ev(stops[i + 1]);
28589
+ if (typeof lo === 'number' && typeof hi === 'number') { return lo + t * (hi - lo); }
28590
+ return t < 0.5 ? lo : hi;
28591
+ }
28592
+ }
28593
+ return ev(stops[stops.length - 1]);
28594
+ }
28595
+ case '+': { var sum = 0; for (var u = 1; u < e.length; u++) { sum += ev(e[u]); } return sum; }
28596
+ case '*': { var prod = 1; for (var w = 1; w < e.length; w++) { prod *= ev(e[w]); } return prod; }
28597
+ case '-': return e.length === 2 ? -ev(e[1]) : ev(e[1]) - ev(e[2]);
28598
+ case '/': return ev(e[1]) / ev(e[2]);
28599
+ default:
28600
+ // A plain array value (an offset, a dash): every member evaluated.
28601
+ return e.map(ev);
28602
+ }
28603
+ }
28604
+
28605
+ // Legacy filters (['==', 'key', value]) are read as expressions too.
28606
+ function passes(filter, ctx) {
28607
+ if (!filter) { return true; }
28608
+ return !!evaluate(filter, ctx);
28609
+ }
28610
+
28611
+ // ------------------------------------------------------------------ clustering (a grid per zoom, like the engine's)
28612
+
28613
+ function clusterAt(features, zoom, radius, maxZoom) {
28614
+ var z = Math.floor(zoom);
28615
+ if (z > maxZoom) { return { features: features, clusters: {} }; }
28616
+ var scale = TILE * Math.pow(2, z), cell = radius;
28617
+ var grid = {}, out = [], clusters = {};
28618
+ features.forEach(function (f) {
28619
+ var g = f.geometry;
28620
+ if (!g || g.type !== 'Point') { out.push(f); return; }
28621
+ var x = lngX(g.coordinates[0], scale), y = latY(g.coordinates[1], scale);
28622
+ var key = Math.floor(x / cell) + ':' + Math.floor(y / cell);
28623
+ (grid[key] = grid[key] || []).push({ f: f, x: x, y: y });
28624
+ });
28625
+ var seq = 0;
28626
+ Object.keys(grid).forEach(function (key) {
28627
+ var members = grid[key];
28628
+ if (members.length === 1) { out.push(members[0].f); return; }
28629
+ var sx = 0, sy = 0;
28630
+ members.forEach(function (m) { sx += m.x; sy += m.y; });
28631
+ var id = z * 100000 + (++seq);
28632
+ var count = members.length;
28633
+ clusters[id] = { leaves: members.map(function (m) { return m.f; }), zoom: z };
28634
+ out.push({ type: 'Feature', id: id, properties: { cluster: true, cluster_id: id, point_count: count, point_count_abbreviated: count >= 1000 ? Math.round(count / 100) / 10 + 'k' : String(count) },
28635
+ geometry: { type: 'Point', coordinates: [xLng(sx / count, scale), yLat(sy / count, scale)] } });
28636
+ });
28637
+ return { features: out, clusters: clusters };
28638
+ }
28639
+
28640
+ function GeoJSONSource(map, id, spec) {
28641
+ this.map = map; this.id = id; this.type = 'geojson'; this.spec = spec;
28642
+ this.setData(spec.data);
28643
+ }
28644
+ GeoJSONSource.prototype.setData = function (data) {
28645
+ var fc = !data ? { type: 'FeatureCollection', features: [] } : (data.type === 'FeatureCollection' ? data : (data.type === 'Feature' ? { type: 'FeatureCollection', features: [data] } : { type: 'FeatureCollection', features: [{ type: 'Feature', properties: {}, geometry: data }] }));
28646
+ var spec = this.spec, idp = spec.promoteId;
28647
+ this.features = fc.features.map(function (f, i) {
28648
+ var id = f.id;
28649
+ if (spec.generateId) { id = i; } else if (idp && f.properties && f.properties[idp] !== undefined) { id = f.properties[idp]; }
28650
+ return id === f.id ? f : Object.assign({}, f, { id: id });
28651
+ });
28652
+ this._clusterZoom = null;
28653
+ this.map._changed();
28654
+ var self = this;
28655
+ setTimeout(function () { self.map._fire('sourcedata', { sourceId: self.id, isSourceLoaded: true, dataType: 'source' }); }, 0);
28656
+ return this;
28657
+ };
28658
+ GeoJSONSource.prototype._shown = function (zoom) {
28659
+ if (!this.spec.cluster) { return this.features; }
28660
+ var z = Math.floor(zoom);
28661
+ if (this._clusterZoom !== z) {
28662
+ var c = clusterAt(this.features, z, (this.spec.clusterRadius || 50) * 1, this.spec.clusterMaxZoom === undefined ? 14 : this.spec.clusterMaxZoom);
28663
+ this._cluster = c; this._clusterZoom = z;
28664
+ }
28665
+ return this._cluster.features;
28666
+ };
28667
+ GeoJSONSource.prototype.getClusterLeaves = function (id, limit, offset) {
28668
+ var c = this._cluster && this._cluster.clusters[id];
28669
+ var leaves = c ? c.leaves : [];
28670
+ return Promise.resolve(leaves.slice(offset || 0, (offset || 0) + (limit === undefined || limit === Infinity ? leaves.length : limit)));
28671
+ };
28672
+ GeoJSONSource.prototype.getClusterExpansionZoom = function (id) {
28673
+ var c = this._cluster && this._cluster.clusters[id];
28674
+ return Promise.resolve(c ? Math.min(c.zoom + 2, (this.spec.clusterMaxZoom === undefined ? 14 : this.spec.clusterMaxZoom) + 1) : this.map.getZoom() + 2);
28675
+ };
28676
+
28677
+ // Raster tiles: loaded as images, kept in a small cache, a parent tile drawn while a tile is on its way.
28678
+ function RasterSource(map, id, spec) {
28679
+ this.map = map; this.id = id; this.type = spec.type; this.spec = spec;
28680
+ this.tiles = {};
28681
+ this.order = [];
28682
+ }
28683
+ RasterSource.prototype._url = function (z, x, y) {
28684
+ var t = this.spec.tiles[(x + y) % this.spec.tiles.length];
28685
+ if (this.spec.scheme === 'tms') { y = Math.pow(2, z) - 1 - y; }
28686
+ return t.replace('{z}', z).replace('{x}', x).replace('{y}', y).replace('{ratio}', '');
28687
+ };
28688
+ RasterSource.prototype.tile = function (z, x, y) {
28689
+ var key = z + '/' + x + '/' + y, t = this.tiles[key];
28690
+ if (t) { return t; }
28691
+ var self = this, url = this._url(z, x, y);
28692
+ t = this.tiles[key] = { img: null, ready: false, failed: false };
28693
+ this.order.push(key);
28694
+ if (this.order.length > 400) { delete this.tiles[this.order.shift()]; }
28695
+ var doc = this.map._doc;
28696
+ var done = function (img) { t.img = img; t.ready = true; self.map._changed(); self.map._fire('sourcedata', { sourceId: self.id, isSourceLoaded: true, tile: { key: key } }); };
28697
+ var fail = function (err) { t.failed = true; self.map._fire('error', { type: 'error', sourceId: self.id, error: err || new Error('tile failed: ' + url) }); };
28698
+ var scheme = /^([a-z][a-z0-9+.-]*):\/\//i.exec(url);
28699
+ var proto = scheme && protocols[scheme[1].toLowerCase()];
28700
+ if (proto) {
28701
+ Promise.resolve(proto({ url: url, type: 'image' }, { signal: null })).then(function (r) {
28702
+ var blob = new Blob([r.data], { type: 'image/png' });
28703
+ var img = new (doc.defaultView.Image)();
28704
+ img.onload = function () { done(img); };
28705
+ img.onerror = function () { fail(); };
28706
+ img.src = URL.createObjectURL(blob);
28707
+ }, fail);
28708
+ return t;
28709
+ }
28710
+ var img = new (doc.defaultView.Image)();
28711
+ img.crossOrigin = 'anonymous';
28712
+ img.onload = function () { done(img); };
28713
+ img.onerror = function () { fail(); };
28714
+ var request = this.map._transform ? this.map._transform(url, 'Tile') : { url: url };
28715
+ img.src = request && request.url ? request.url : url;
28716
+ return t;
28717
+ };
28718
+
28719
+ var protocols = {};
28720
+ function addProtocol(name, fn) { protocols[String(name).toLowerCase()] = fn; }
28721
+ function removeProtocol(name) { delete protocols[String(name).toLowerCase()]; }
28722
+
28723
+ // ------------------------------------------------------------------ the map
28724
+
28725
+ var CORNERS = ['top-left', 'top-right', 'bottom-left', 'bottom-right'];
28726
+
28727
+ function Handler(map, name) { this.map = map; this.name = name; this.on = true; }
28728
+ Handler.prototype.enable = function () { this.on = true; };
28729
+ Handler.prototype.disable = function () { this.on = false; if (this.name === 'dragPan') { this.map._drag = null; } };
28730
+ Handler.prototype.isEnabled = function () { return this.on; };
28731
+
28732
+ /**
28733
+ * The canvas map. Options as the engine's: container, style ({ sources, layers } with raster sources), center,
28734
+ * zoom, minZoom, maxZoom, attributionControl, transformRequest.
28735
+ */
28736
+ function CanvasMap(options) {
28737
+ var self = this;
28738
+ this._doc = null;
28739
+ var container = typeof options.container === 'string' ? document.getElementById(options.container) : options.container;
28740
+ if (!container) { throw new Error('sMap: no map container'); }
28741
+ this._doc = container.ownerDocument;
28742
+ this._container = container;
28743
+ this._transform = options.transformRequest || null;
28744
+ this._events = {};
28745
+ this._layerEvents = [];
28746
+ this._sources = {};
28747
+ this._layers = [];
28748
+ this._images = {};
28749
+ this._controls = [];
28750
+ this._center = toLngLat(options.center || [0, 0]);
28751
+ this._zoom = options.zoom || 0;
28752
+ this._minZoom = options.minZoom !== undefined ? options.minZoom : 0;
28753
+ this._maxZoom = options.maxZoom !== undefined ? options.maxZoom : 22;
28754
+ this._drawn = [];
28755
+ this._dirty = false;
28756
+ container.classList.add('maplibregl-map', 'smap-canvas-map');
28757
+ var canvasContainer = this._doc.createElement('div');
28758
+ canvasContainer.className = 'maplibregl-canvas-container maplibregl-interactive';
28759
+ var canvas = this._doc.createElement('canvas');
28760
+ canvas.className = 'maplibregl-canvas';
28761
+ canvas.setAttribute('tabindex', '0');
28762
+ canvas.style.position = 'absolute'; canvas.style.left = '0'; canvas.style.top = '0';
28763
+ canvasContainer.appendChild(canvas);
28764
+ container.appendChild(canvasContainer);
28765
+ var controls = this._doc.createElement('div');
28766
+ controls.className = 'maplibregl-control-container';
28767
+ this._corners = {};
28768
+ CORNERS.forEach(function (c) {
28769
+ var el = self._doc.createElement('div');
28770
+ el.className = 'maplibregl-ctrl-' + c;
28771
+ controls.appendChild(el);
28772
+ self._corners[c] = el;
28773
+ });
28774
+ container.appendChild(controls);
28775
+ this._canvas = canvas;
28776
+ this._canvasContainer = canvasContainer;
28777
+ this.dragPan = new Handler(this, 'dragPan');
28778
+ this.scrollZoom = new Handler(this, 'scrollZoom');
28779
+ this.boxZoom = new Handler(this, 'boxZoom');
28780
+ this.doubleClickZoom = new Handler(this, 'doubleClickZoom');
28781
+ this.touchZoomRotate = new Handler(this, 'touchZoomRotate');
28782
+ this.keyboard = new Handler(this, 'keyboard');
28783
+ this.dragRotate = new Handler(this, 'dragRotate');
28784
+ this._resize();
28785
+ this._input();
28786
+ if (options.attributionControl !== false) { this.addControl(new AttributionControl(options.attributionControl || {}), 'bottom-right'); }
28787
+ this.setStyle(options.style);
28788
+ var win = this._doc.defaultView;
28789
+ if (win && win.ResizeObserver) {
28790
+ this._ro = new win.ResizeObserver(function () { self.resize(); });
28791
+ this._ro.observe(container);
28792
+ } else if (win) { win.addEventListener('resize', function () { self.resize(); }); }
28793
+ setTimeout(function () { self._fire('load', {}); }, 0);
28794
+ }
28795
+
28796
+ CanvasMap.prototype.isCanvas = true;
28797
+
28798
+ // ---- events
28799
+ CanvasMap.prototype.on = function (type, layer, fn) {
28800
+ if (typeof layer === 'function') { (this._events[type] = this._events[type] || []).push(layer); return this; }
28801
+ this._layerEvents.push({ type: type, layer: layer, fn: fn, inside: false });
28802
+ return this;
28803
+ };
28804
+ CanvasMap.prototype.off = function (type, layer, fn) {
28805
+ if (typeof layer === 'function') { this._events[type] = (this._events[type] || []).filter(function (f) { return f !== layer; }); return this; }
28806
+ this._layerEvents = this._layerEvents.filter(function (h) { return !(h.type === type && h.layer === layer && h.fn === fn); });
28807
+ return this;
28808
+ };
28809
+ CanvasMap.prototype.once = function (type, fn) {
28810
+ var self = this;
28811
+ var wrapped = function (e) { self.off(type, wrapped); if (fn) { fn(e); } };
28812
+ if (!fn) { return new Promise(function (resolve) { fn = resolve; self.on(type, wrapped); }); }
28813
+ return this.on(type, wrapped);
28814
+ };
28815
+ CanvasMap.prototype.fire = function (e) { this._fire(e.type, e); return this; };
28816
+ CanvasMap.prototype._fire = function (type, data) {
28817
+ var e = data || {};
28818
+ e.type = type;
28819
+ e.target = this;
28820
+ (this._events[type] || []).slice().forEach(function (fn) { fn(e); });
28821
+ return e;
28822
+ };
28823
+
28824
+ // ---- camera
28825
+ CanvasMap.prototype._scale = function (z) { return TILE * Math.pow(2, z === undefined ? this._zoom : z); };
28826
+ CanvasMap.prototype.getContainer = function () { return this._container; };
28827
+ CanvasMap.prototype.getCanvas = function () { return this._canvas; };
28828
+ CanvasMap.prototype.getCanvasContainer = function () { return this._canvasContainer; };
28829
+ CanvasMap.prototype.getCenter = function () { return new LngLat(this._center.lng, this._center.lat); };
28830
+ CanvasMap.prototype.getZoom = function () { return this._zoom; };
28831
+ CanvasMap.prototype.getBearing = function () { return 0; };
28832
+ CanvasMap.prototype.getPitch = function () { return 0; };
28833
+ CanvasMap.prototype.getMinZoom = function () { return this._minZoom; };
28834
+ CanvasMap.prototype.getMaxZoom = function () { return this._maxZoom; };
28835
+ CanvasMap.prototype.setMinZoom = function (z) { this._minZoom = z; return this; };
28836
+ CanvasMap.prototype.setMaxZoom = function (z) { this._maxZoom = z; return this; };
28837
+ CanvasMap.prototype.project = function (v) {
28838
+ var p = toLngLat(v), s = this._scale();
28839
+ return { x: lngX(p.lng, s) - lngX(this._center.lng, s) + this._w / 2, y: latY(p.lat, s) - latY(this._center.lat, s) + this._h / 2 };
28840
+ };
28841
+ CanvasMap.prototype.unproject = function (pt) {
28842
+ var x = Array.isArray(pt) ? pt[0] : pt.x, y = Array.isArray(pt) ? pt[1] : pt.y, s = this._scale();
28843
+ return new LngLat(xLng(lngX(this._center.lng, s) + x - this._w / 2, s), yLat(latY(this._center.lat, s) + y - this._h / 2, s));
28844
+ };
28845
+ CanvasMap.prototype.getBounds = function () {
28846
+ var nw = this.unproject([0, 0]), se = this.unproject([this._w, this._h]);
28847
+ return new LngLatBounds([nw.lng, se.lat], [se.lng, nw.lat]);
28848
+ };
28849
+ CanvasMap.prototype._set = function (center, zoom) {
28850
+ var zoomed = zoom !== undefined && zoom !== this._zoom;
28851
+ if (center) { var c = toLngLat(center); this._center = { lng: ((c.lng + 540) % 360) - 180, lat: clampLat(c.lat) }; }
28852
+ if (zoom !== undefined) { this._zoom = Math.max(this._minZoom, Math.min(this._maxZoom, zoom)); }
28853
+ this._changed(true);
28854
+ this._fire('move', {});
28855
+ if (zoomed) { this._fire('zoom', {}); }
28856
+ };
28857
+ CanvasMap.prototype._end = function (zoomed) { this._fire('moveend', {}); if (zoomed) { this._fire('zoomend', {}); } this._fire('idle', {}); };
28858
+ CanvasMap.prototype.jumpTo = function (o) {
28859
+ var z0 = this._zoom;
28860
+ this._set(o.center, o.zoom);
28861
+ this._end(this._zoom !== z0);
28862
+ return this;
28863
+ };
28864
+ CanvasMap.prototype.easeTo = function (o) {
28865
+ var self = this, from = this.getCenter(), z0 = this._zoom;
28866
+ var to = o.center ? toLngLat(o.center) : from, z1 = o.zoom !== undefined ? o.zoom : z0;
28867
+ if (o.offset) { var p = this.project(to); to = this.unproject([p.x - o.offset[0], p.y - o.offset[1]]); }
28868
+ var duration = o.duration === undefined ? 300 : o.duration, start = null, seq = ++this._anim;
28869
+ if (!duration) { return this.jumpTo({ center: to, zoom: z1 }); }
28870
+ var step = function (now) {
28871
+ if (seq !== self._anim) { return; }
28872
+ if (start === null) { start = now; }
28873
+ var t = Math.min(1, (now - start) / duration), k = 1 - Math.pow(1 - t, 3);
28874
+ // Zoom moves evenly in its own scale; the centre follows in world pixels of the zoom reached.
28875
+ var z = z0 + (z1 - z0) * k;
28876
+ var s = TILE * Math.pow(2, z);
28877
+ var x = lngX(from.lng, s) + (lngX(to.lng, s) - lngX(from.lng, s)) * k, y = latY(from.lat, s) + (latY(to.lat, s) - latY(from.lat, s)) * k;
28878
+ self._set([xLng(x, s), yLat(y, s)], z);
28879
+ if (t < 1) { raf(step); } else { self._end(z1 !== z0); }
28880
+ };
28881
+ raf(step);
28882
+ return this;
28883
+ };
28884
+ CanvasMap.prototype._anim = 0;
28885
+ CanvasMap.prototype.flyTo = function (o) { return this.easeTo(Object.assign({ duration: o.duration === undefined ? 800 : o.duration }, o)); };
28886
+ CanvasMap.prototype.panBy = function (offset, o) {
28887
+ var c = this.project(this._center);
28888
+ return this.easeTo(Object.assign({ center: this.unproject([c.x + offset[0], c.y + offset[1]]) }, o || {}));
28889
+ };
28890
+ CanvasMap.prototype.panTo = function (center, o) { return this.easeTo(Object.assign({ center: center }, o || {})); };
28891
+ CanvasMap.prototype.zoomTo = function (z, o) { return this.easeTo(Object.assign({ zoom: z }, o || {})); };
28892
+ CanvasMap.prototype.zoomIn = function (o) { return this.zoomTo(this._zoom + 1, o); };
28893
+ CanvasMap.prototype.zoomOut = function (o) { return this.zoomTo(this._zoom - 1, o); };
28894
+ CanvasMap.prototype.setCenter = function (c) { return this.jumpTo({ center: c }); };
28895
+ CanvasMap.prototype.setZoom = function (z) { return this.jumpTo({ zoom: z }); };
28896
+ CanvasMap.prototype.cameraForBounds = function (bounds, o) {
28897
+ var b = bounds instanceof LngLatBounds ? bounds : new LngLatBounds(bounds);
28898
+ if (b.isEmpty()) { return null; }
28899
+ o = o || {};
28900
+ var pad = typeof o.padding === 'number' ? { top: o.padding, bottom: o.padding, left: o.padding, right: o.padding } : Object.assign({ top: 0, bottom: 0, left: 0, right: 0 }, o.padding || {});
28901
+ var w = Math.max(1, this._w - pad.left - pad.right), h = Math.max(1, this._h - pad.top - pad.bottom);
28902
+ var s1 = TILE, dx = Math.abs(lngX(b.getEast(), s1) - lngX(b.getWest(), s1)), dy = Math.abs(latY(b.getSouth(), s1) - latY(b.getNorth(), s1));
28903
+ var z = Math.min(Math.log2(w / Math.max(dx, 1e-9)), Math.log2(h / Math.max(dy, 1e-9)));
28904
+ z = Math.min(z, o.maxZoom !== undefined ? o.maxZoom : this._maxZoom);
28905
+ var c = b.getCenter(), s = TILE * Math.pow(2, z);
28906
+ // The padding moves the centre.
28907
+ var cx = lngX(c.lng, s) - (pad.left - pad.right) / 2, cy = latY(c.lat, s) - (pad.top - pad.bottom) / 2;
28908
+ return { center: [xLng(cx, s), yLat(cy, s)], zoom: z };
28909
+ };
28910
+ CanvasMap.prototype.fitBounds = function (bounds, o) {
28911
+ var cam = this.cameraForBounds(bounds, o);
28912
+ if (!cam) { return this; }
28913
+ return this.easeTo(Object.assign({}, cam, { duration: o && o.duration !== undefined ? o.duration : (o && o.animate === false ? 0 : 300) }));
28914
+ };
28915
+ CanvasMap.prototype.setProjection = function () { return this; };
28916
+ CanvasMap.prototype.getProjection = function () { return { type: 'mercator' }; };
28917
+ CanvasMap.prototype.setTerrain = function (t) { if (t) { this._unsupported('terrain'); } return this; };
28918
+ CanvasMap.prototype._unsupported = function (what) {
28919
+ this._said = this._said || {};
28920
+ if (this._said[what]) { return; }
28921
+ this._said[what] = true;
28922
+ this._fire('smap.unsupported', { feature: what });
28923
+ };
28924
+
28925
+ CanvasMap.prototype.resize = function () { if (this._resize()) { this._changed(true); this._fire('resize', {}); this._fire('moveend', {}); } return this; };
28926
+ CanvasMap.prototype._resize = function () {
28927
+ var w = this._container.clientWidth || 300, h = this._container.clientHeight || 150;
28928
+ var win = this._doc.defaultView || {}, ratio = Math.min(3, win.devicePixelRatio || 1);
28929
+ if (w === this._w && h === this._h && ratio === this._ratio) { return false; }
28930
+ this._w = w; this._h = h; this._ratio = ratio;
28931
+ this._canvas.width = Math.round(w * ratio); this._canvas.height = Math.round(h * ratio);
28932
+ this._canvas.style.width = w + 'px'; this._canvas.style.height = h + 'px';
28933
+ return true;
28934
+ };
28935
+ CanvasMap.prototype.triggerRepaint = function () { this._changed(); };
28936
+ CanvasMap.prototype._changed = function () {
28937
+ if (this._dirty || this._removed) { return; }
28938
+ this._dirty = true;
28939
+ var self = this;
28940
+ raf(function () { self._dirty = false; self._render(); });
28941
+ };
28942
+ CanvasMap.prototype.loaded = function () { return true; };
28943
+ CanvasMap.prototype.isStyleLoaded = function () { return true; };
28944
+ CanvasMap.prototype.remove = function () {
28945
+ this._removed = true;
28946
+ if (this._ro) { this._ro.disconnect(); }
28947
+ if (this._canvasContainer.parentNode) { this._canvasContainer.parentNode.removeChild(this._canvasContainer); }
28948
+ var cc = this._container.querySelector('.maplibregl-control-container');
28949
+ if (cc) { cc.parentNode.removeChild(cc); }
28950
+ this._fire('remove', {});
28951
+ };
28952
+
28953
+ // ---- style, sources, layers
28954
+ CanvasMap.prototype.setStyle = function (style) {
28955
+ var self = this;
28956
+ this._sources = {};
28957
+ this._layers = [];
28958
+ style = style && typeof style === 'object' ? style : { sources: {}, layers: [] };
28959
+ Object.keys(style.sources || {}).forEach(function (id) { self.addSource(id, style.sources[id]); });
28960
+ (style.layers || []).forEach(function (l) { self.addLayer(l); });
28961
+ this._changed();
28962
+ setTimeout(function () { self._fire('style.load', {}); self._fire('styledata', {}); }, 0);
28963
+ return this;
28964
+ };
28965
+ CanvasMap.prototype.getStyle = function () {
28966
+ var self = this, sources = {};
28967
+ Object.keys(this._sources).forEach(function (id) { sources[id] = self._sources[id].spec; });
28968
+ return { version: 8, sources: sources, layers: this._layers.map(function (l) { return l; }) };
28969
+ };
28970
+ CanvasMap.prototype.addSource = function (id, spec) {
28971
+ if (this._sources[id]) { throw new Error('There is already a source with this ID'); }
28972
+ if (spec.type === 'geojson') { this._sources[id] = new GeoJSONSource(this, id, spec); }
28973
+ else if (spec.type === 'raster' && spec.tiles) { this._sources[id] = new RasterSource(this, id, spec); }
28974
+ else { this._sources[id] = { id: id, type: spec.type, spec: spec, setData: function () {} }; if (spec.type !== 'raster-dem') { this._unsupported('source:' + spec.type); } }
28975
+ this._updateAttribution();
28976
+ return this;
28977
+ };
28978
+ CanvasMap.prototype.getSource = function (id) { return this._sources[id]; };
28979
+ CanvasMap.prototype.removeSource = function (id) { delete this._sources[id]; this._updateAttribution(); this._changed(); return this; };
28980
+ CanvasMap.prototype.addLayer = function (layer, before) {
28981
+ if (this.getLayer(layer.id)) { throw new Error('Layer with id "' + layer.id + '" already exists'); }
28982
+ var l = layer.type === 'custom' ? layer : JSON.parse(JSON.stringify(layer));
28983
+ if (typeof l.source === 'object' && l.source) { this.addSource(l.id, l.source); l.source = l.id; }
28984
+ if (['raster', 'fill', 'line', 'circle', 'symbol', 'heatmap', 'background', 'fill-extrusion'].indexOf(l.type) < 0) { this._unsupported('layer:' + l.type); }
28985
+ var at = before ? this._layers.findIndex(function (x) { return x.id === before; }) : -1;
28986
+ if (at >= 0) { this._layers.splice(at, 0, l); } else { this._layers.push(l); }
28987
+ if (l.type === 'custom' && l.onAdd) { this._unsupported('3d'); }
28988
+ this._changed();
28989
+ return this;
28990
+ };
28991
+ CanvasMap.prototype.getLayer = function (id) { for (var i = 0; i < this._layers.length; i++) { if (this._layers[i].id === id) { return this._layers[i]; } } return undefined; };
28992
+ CanvasMap.prototype.removeLayer = function (id) { this._layers = this._layers.filter(function (l) { return l.id !== id; }); this._changed(); return this; };
28993
+ CanvasMap.prototype.moveLayer = function (id, before) {
28994
+ var l = this.getLayer(id);
28995
+ if (!l) { return this; }
28996
+ this._layers = this._layers.filter(function (x) { return x !== l; });
28997
+ var at = before ? this._layers.findIndex(function (x) { return x.id === before; }) : -1;
28998
+ if (at >= 0) { this._layers.splice(at, 0, l); } else { this._layers.push(l); }
28999
+ this._changed();
29000
+ return this;
29001
+ };
29002
+ CanvasMap.prototype.setLayoutProperty = function (id, k, v) { var l = this.getLayer(id); if (l) { l.layout = Object.assign({}, l.layout, {}); l.layout[k] = v; this._changed(); } return this; };
29003
+ CanvasMap.prototype.getLayoutProperty = function (id, k) { var l = this.getLayer(id); return l && l.layout ? l.layout[k] : undefined; };
29004
+ CanvasMap.prototype.setPaintProperty = function (id, k, v) { var l = this.getLayer(id); if (l) { l.paint = Object.assign({}, l.paint, {}); l.paint[k] = v; this._changed(); } return this; };
29005
+ CanvasMap.prototype.getPaintProperty = function (id, k) { var l = this.getLayer(id); return l && l.paint ? l.paint[k] : undefined; };
29006
+ CanvasMap.prototype.setFilter = function (id, f) { var l = this.getLayer(id); if (l) { l.filter = f || undefined; this._changed(); } return this; };
29007
+ CanvasMap.prototype.getFilter = function (id) { var l = this.getLayer(id); return l ? l.filter : undefined; };
29008
+ CanvasMap.prototype.setLayerZoomRange = function (id, min, max) { var l = this.getLayer(id); if (l) { l.minzoom = min; l.maxzoom = max; this._changed(); } return this; };
29009
+
29010
+ // ---- images (the SDK's drawn pins, numbers, badges and arrows; icons)
29011
+ CanvasMap.prototype.hasImage = function (id) { return !!this._images[id]; };
29012
+ CanvasMap.prototype.addImage = function (id, image, o) {
29013
+ var ratio = (o && o.pixelRatio) || 1, canvas;
29014
+ if (image && image.data && image.width !== undefined && !(image.getContext)) {
29015
+ canvas = this._doc.createElement('canvas');
29016
+ canvas.width = image.width; canvas.height = image.height;
29017
+ var ctx = canvas.getContext('2d');
29018
+ var data = ctx.createImageData(image.width, image.height);
29019
+ data.data.set(image.data);
29020
+ ctx.putImageData(data, 0, 0);
29021
+ } else { canvas = image; }
29022
+ this._images[id] = { source: canvas, ratio: ratio, w: (canvas.width || canvas.naturalWidth) / ratio, h: (canvas.height || canvas.naturalHeight) / ratio };
29023
+ this._changed();
29024
+ return this;
29025
+ };
29026
+ CanvasMap.prototype.removeImage = function (id) { delete this._images[id]; return this; };
29027
+ CanvasMap.prototype.loadImage = function (url) {
29028
+ var doc = this._doc;
29029
+ return new Promise(function (resolve, reject) {
29030
+ var img = new (doc.defaultView.Image)();
29031
+ img.crossOrigin = 'anonymous';
29032
+ img.onload = function () { resolve({ data: img }); };
29033
+ img.onerror = function () { reject(new Error('sMap: image failed ' + url)); };
29034
+ img.src = url;
29035
+ });
29036
+ };
29037
+ CanvasMap.prototype.setMissingStyleImageResolver = function (fn) { this._missing = fn; return this; };
29038
+ CanvasMap.prototype._image = function (id) {
29039
+ if (!this._images[id] && this._missing) { this._missing(id); }
29040
+ return this._images[id] || null;
29041
+ };
29042
+
29043
+ // ---- controls
29044
+ CanvasMap.prototype.addControl = function (control, position) {
29045
+ var pos = position || (control.getDefaultPosition && control.getDefaultPosition()) || 'top-right';
29046
+ var el = control.onAdd(this);
29047
+ var corner = this._corners[pos];
29048
+ if (pos.indexOf('bottom') === 0) { corner.insertBefore(el, corner.firstChild); } else { corner.appendChild(el); }
29049
+ this._controls.push(control);
29050
+ return this;
29051
+ };
29052
+ CanvasMap.prototype.removeControl = function (control) {
29053
+ this._controls = this._controls.filter(function (c) { return c !== control; });
29054
+ if (control.onRemove) { control.onRemove(this); }
29055
+ return this;
29056
+ };
29057
+ CanvasMap.prototype.hasControl = function (control) { return this._controls.indexOf(control) >= 0; };
29058
+ CanvasMap.prototype._updateAttribution = function () {
29059
+ var self = this, seen = {}, parts = [];
29060
+ Object.keys(this._sources).forEach(function (id) { var a = self._sources[id].spec && self._sources[id].spec.attribution; if (a && !seen[a]) { seen[a] = true; parts.push(a); } });
29061
+ this._attribution = parts.join(' | ');
29062
+ this._controls.forEach(function (c) { if (c instanceof AttributionControl) { c._update(); } });
29063
+ };
29064
+
29065
+ // ---- drawing
29066
+
29067
+ CanvasMap.prototype._visible = function (l) {
29068
+ if (l.layout && l.layout.visibility === 'none') { return false; }
29069
+ if (l.minzoom !== undefined && this._zoom < l.minzoom) { return false; }
29070
+ if (l.maxzoom !== undefined && this._zoom >= l.maxzoom) { return false; }
29071
+ return true;
29072
+ };
29073
+
29074
+ CanvasMap.prototype._render = function () {
29075
+ var ctx = this._canvas.getContext('2d');
29076
+ if (!ctx) { return; }
29077
+ var r = this._ratio;
29078
+ ctx.setTransform(r, 0, 0, r, 0, 0);
29079
+ ctx.clearRect(0, 0, this._w, this._h);
29080
+ this._drawn = [];
29081
+ var self = this, zoom = this._zoom;
29082
+ // Raster layers first (the street map, imagery), then every other layer in its order.
29083
+ var rasters = this._layers.filter(function (l) { return l.type === 'raster' || l.type === 'background'; });
29084
+ var others = this._layers.filter(function (l) { return l.type !== 'raster' && l.type !== 'background'; });
29085
+ rasters.concat(others).forEach(function (l) {
29086
+ if (!self._visible(l)) { return; }
29087
+ if (l.type === 'background') { ctx.fillStyle = evaluate((l.paint || {})['background-color'], { zoom: zoom }) || '#ffffff'; ctx.fillRect(0, 0, self._w, self._h); return; }
29088
+ if (l.type === 'raster') { self._drawRaster(ctx, l); return; }
29089
+ var src = self._sources[l.source];
29090
+ if (!src || !src._shown) { return; }
29091
+ var features = src._shown(zoom);
29092
+ if (l.type === 'heatmap') { self._drawHeatmap(ctx, l, features); return; }
29093
+ for (var i = 0; i < features.length; i++) {
29094
+ var f = features[i], c = { zoom: zoom, f: f };
29095
+ if (!f.geometry || !passes(l.filter, c)) { continue; }
29096
+ if (l.type === 'fill' || l.type === 'fill-extrusion') { self._drawFill(ctx, l, f, c); }
29097
+ else if (l.type === 'line') { self._drawLine(ctx, l, f, c); }
29098
+ else if (l.type === 'circle') { self._drawCircle(ctx, l, f, c); }
29099
+ else if (l.type === 'symbol') { self._drawSymbol(ctx, l, f, c); }
29100
+ }
29101
+ });
29102
+ this._fire('render', {});
29103
+ };
29104
+
29105
+ CanvasMap.prototype._drawRaster = function (ctx, l) {
29106
+ var src = this._sources[l.source];
29107
+ if (!src || !src.tile) { return; }
29108
+ var spec = src.spec, ts = spec.tileSize || 256;
29109
+ // The tile zoom whose tiles are closest to their own size at this zoom.
29110
+ var tz = Math.round(this._zoom + Math.log2(TILE / ts));
29111
+ tz = Math.max(spec.minzoom || 0, Math.min(tz, spec.maxzoom === undefined ? 22 : spec.maxzoom));
29112
+ var n = Math.pow(2, tz), size = this._scale() / n;
29113
+ var s = this._scale();
29114
+ var ox = lngX(this._center.lng, s) - this._w / 2, oy = latY(this._center.lat, s) - this._h / 2;
29115
+ var x0 = Math.floor(ox / size), x1 = Math.floor((ox + this._w) / size), y0 = Math.max(0, Math.floor(oy / size)), y1 = Math.min(n - 1, Math.floor((oy + this._h) / size));
29116
+ var opacity = (l.paint && l.paint['raster-opacity'] !== undefined) ? l.paint['raster-opacity'] : 1;
29117
+ ctx.save();
29118
+ ctx.globalAlpha = opacity;
29119
+ ctx.imageSmoothingEnabled = true;
29120
+ for (var x = x0; x <= x1; x++) {
29121
+ for (var y = y0; y <= y1; y++) {
29122
+ var wx = ((x % n) + n) % n;
29123
+ var px = x * size - ox, py = y * size - oy;
29124
+ var t = src.tile(tz, wx, y);
29125
+ if (t.ready) { ctx.drawImage(t.img, px, py, size + 0.5, size + 0.5); continue; }
29126
+ // A parent tile already loaded, enlarged, while this one is on its way.
29127
+ for (var up = 1; up <= 4 && tz - up >= 0; up++) {
29128
+ var pz = tz - up, k = Math.pow(2, up), pt = src.tiles[pz + '/' + Math.floor(wx / k) + '/' + Math.floor(y / k)];
29129
+ if (pt && pt.ready) {
29130
+ var sw = pt.img.width / k, sx = (wx % k) * sw, sy = (y % k) * (pt.img.height / k);
29131
+ ctx.drawImage(pt.img, sx, sy, sw, pt.img.height / k, px, py, size + 0.5, size + 0.5);
29132
+ break;
29133
+ }
29134
+ }
29135
+ }
29136
+ }
29137
+ ctx.restore();
29138
+ };
29139
+
29140
+ // Screen points of a geometry's parts: [{ type, rings: [[[x, y], …]] }].
29141
+ CanvasMap.prototype._screen = function (g) {
29142
+ var self = this, s = this._scale();
29143
+ var ox = lngX(this._center.lng, s) - this._w / 2, oy = latY(this._center.lat, s) - this._h / 2;
29144
+ var pt = function (c) { return [lngX(c[0], s) - ox, latY(c[1], s) - oy]; };
29145
+ var line = function (cs) { return cs.map(pt); };
29146
+ switch (g.type) {
29147
+ case 'Point': return [pt(g.coordinates)];
29148
+ case 'MultiPoint': return g.coordinates.map(pt);
29149
+ case 'LineString': return [line(g.coordinates)];
29150
+ case 'MultiLineString': return g.coordinates.map(line);
29151
+ case 'Polygon': return [g.coordinates.map(line)];
29152
+ case 'MultiPolygon': return g.coordinates.map(function (p) { return p.map(line); });
29153
+ default: return [];
29154
+ }
29155
+ };
29156
+
29157
+ function paintOf(l, k, c, d) { var v = l.paint ? l.paint[k] : undefined; v = v === undefined ? d : evaluate(v, c); return v === undefined || v === null ? d : v; }
29158
+ function layoutOf(l, k, c, d) { var v = l.layout ? l.layout[k] : undefined; v = v === undefined ? d : evaluate(v, c); return v === undefined || v === null ? d : v; }
29159
+
29160
+ CanvasMap.prototype._record = function (l, f, hit) { this._drawn.push({ layer: l, f: f, hit: hit }); };
29161
+
29162
+ CanvasMap.prototype._drawFill = function (ctx, l, f, c) {
29163
+ var g = f.geometry;
29164
+ if (g.type !== 'Polygon' && g.type !== 'MultiPolygon') { return; }
29165
+ var polys = this._screen(g);
29166
+ ctx.save();
29167
+ ctx.globalAlpha = paintOf(l, l.type === 'fill' ? 'fill-opacity' : 'fill-extrusion-opacity', c, 1);
29168
+ ctx.fillStyle = paintOf(l, l.type === 'fill' ? 'fill-color' : 'fill-extrusion-color', c, '#000000');
29169
+ ctx.beginPath();
29170
+ polys.forEach(function (rings) { rings.forEach(function (ring) { ring.forEach(function (p, i) { if (i) { ctx.lineTo(p[0], p[1]); } else { ctx.moveTo(p[0], p[1]); } }); ctx.closePath(); }); });
29171
+ ctx.fill('evenodd');
29172
+ ctx.restore();
29173
+ this._record(l, f, { kind: 'fill', polys: polys });
29174
+ };
29175
+
29176
+ CanvasMap.prototype._drawLine = function (ctx, l, f, c) {
29177
+ var g = f.geometry, lines;
29178
+ if (g.type === 'LineString' || g.type === 'MultiLineString') { lines = this._screen(g); }
29179
+ else if (g.type === 'Polygon' || g.type === 'MultiPolygon') { lines = []; this._screen(g).forEach(function (rings) { rings.forEach(function (r) { lines.push(r); }); }); }
29180
+ else { return; }
29181
+ var width = paintOf(l, 'line-width', c, 1);
29182
+ ctx.save();
29183
+ ctx.globalAlpha = paintOf(l, 'line-opacity', c, 1);
29184
+ ctx.strokeStyle = paintOf(l, 'line-color', c, '#000000');
29185
+ ctx.lineWidth = width;
29186
+ ctx.lineCap = layoutOf(l, 'line-cap', c, 'butt');
29187
+ ctx.lineJoin = layoutOf(l, 'line-join', c, 'miter');
29188
+ var dash = paintOf(l, 'line-dasharray', c, null);
29189
+ if (Array.isArray(dash)) { ctx.setLineDash(dash.map(function (d) { return d * width; })); }
29190
+ ctx.beginPath();
29191
+ lines.forEach(function (line) { line.forEach(function (p, i) { if (i) { ctx.lineTo(p[0], p[1]); } else { ctx.moveTo(p[0], p[1]); } }); });
29192
+ ctx.stroke();
29193
+ ctx.restore();
29194
+ this._record(l, f, { kind: 'line', lines: lines, width: width });
29195
+ };
29196
+
29197
+ CanvasMap.prototype._drawCircle = function (ctx, l, f, c) {
29198
+ var self = this, radius = paintOf(l, 'circle-radius', c, 5), sw = paintOf(l, 'circle-stroke-width', c, 0);
29199
+ this._screen(f.geometry).forEach(function (p) {
29200
+ if (!Array.isArray(p) || typeof p[0] !== 'number') { return; }
29201
+ if (p[0] < -radius - 50 || p[1] < -radius - 50 || p[0] > self._w + radius + 50 || p[1] > self._h + radius + 50) { return; }
29202
+ ctx.save();
29203
+ ctx.globalAlpha = paintOf(l, 'circle-opacity', c, 1);
29204
+ ctx.beginPath();
29205
+ ctx.arc(p[0], p[1], radius, 0, Math.PI * 2);
29206
+ ctx.fillStyle = paintOf(l, 'circle-color', c, '#000000');
29207
+ ctx.fill();
29208
+ if (sw > 0) { ctx.lineWidth = sw; ctx.strokeStyle = paintOf(l, 'circle-stroke-color', c, '#000000'); ctx.globalAlpha = paintOf(l, 'circle-stroke-opacity', c, 1); ctx.stroke(); }
29209
+ ctx.restore();
29210
+ self._record(l, f, { kind: 'circle', x: p[0], y: p[1], r: radius + sw / 2 });
29211
+ });
29212
+ };
29213
+
29214
+ var ANCHOR_SHIFT = {
29215
+ center: [-0.5, -0.5], top: [-0.5, 0], bottom: [-0.5, -1], left: [0, -0.5], right: [-1, -0.5],
29216
+ 'top-left': [0, 0], 'top-right': [-1, 0], 'bottom-left': [0, -1], 'bottom-right': [-1, -1],
29217
+ };
29218
+
29219
+ CanvasMap.prototype._drawSymbol = function (ctx, l, f, c) {
29220
+ var self = this;
29221
+ var placement = layoutOf(l, 'symbol-placement', c, 'point');
29222
+ var iconId = layoutOf(l, 'icon-image', c, null);
29223
+ var text = layoutOf(l, 'text-field', c, null);
29224
+ if (Array.isArray(text)) { text = text.join(''); }
29225
+ if (placement === 'line') {
29226
+ var g = f.geometry;
29227
+ if (g.type !== 'LineString' && g.type !== 'MultiLineString') { return; }
29228
+ var spacing = layoutOf(l, 'symbol-spacing', c, 250);
29229
+ this._screen(g).forEach(function (line) {
29230
+ var walked = spacing / 2;
29231
+ for (var i = 1; i < line.length; i++) {
29232
+ var a = line[i - 1], b = line[i], len = Math.sqrt(Math.pow(b[0] - a[0], 2) + Math.pow(b[1] - a[1], 2));
29233
+ while (walked <= len) {
29234
+ var t = walked / len, x = a[0] + (b[0] - a[0]) * t, y = a[1] + (b[1] - a[1]) * t;
29235
+ var angle = Math.atan2(b[1] - a[1], b[0] - a[0]);
29236
+ if (x > -50 && y > -50 && x < self._w + 50 && y < self._h + 50) {
29237
+ if (iconId) { self._icon(ctx, l, c, iconId, x, y, angle); }
29238
+ if (text) { self._text(ctx, l, c, String(text), x, y, angle > Math.PI / 2 || angle < -Math.PI / 2 ? angle + Math.PI : angle); }
29239
+ }
29240
+ walked += spacing;
29241
+ }
29242
+ walked -= len;
29243
+ }
29244
+ });
29245
+ return;
29246
+ }
29247
+ this._screen(f.geometry).forEach(function (p) {
29248
+ if (!Array.isArray(p) || typeof p[0] !== 'number') { return; }
29249
+ if (p[0] < -100 || p[1] < -100 || p[0] > self._w + 100 || p[1] > self._h + 100) { return; }
29250
+ var box = null;
29251
+ if (iconId) { box = self._icon(ctx, l, c, iconId, p[0], p[1], 0); }
29252
+ if (text !== null && text !== undefined && text !== '') { var tb = self._text(ctx, l, c, String(text), p[0], p[1], 0); box = box || tb; }
29253
+ if (box) { self._record(l, f, { kind: 'box', box: box }); }
29254
+ });
29255
+ };
29256
+
29257
+ CanvasMap.prototype._icon = function (ctx, l, c, id, x, y, angle) {
29258
+ var img = this._image(String(id));
29259
+ if (!img) { return null; }
29260
+ var size = layoutOf(l, 'icon-size', c, 1);
29261
+ var w = img.w * size, h = img.h * size;
29262
+ var anchor = ANCHOR_SHIFT[layoutOf(l, 'icon-anchor', c, 'center')] || ANCHOR_SHIFT.center;
29263
+ var off = layoutOf(l, 'icon-offset', c, [0, 0]);
29264
+ var dx = off[0] * size + anchor[0] * w, dy = off[1] * size + anchor[1] * h;
29265
+ ctx.save();
29266
+ ctx.globalAlpha = paintOf(l, 'icon-opacity', c, 1);
29267
+ ctx.translate(x, y);
29268
+ if (angle) { ctx.rotate(angle); }
29269
+ ctx.drawImage(img.source, dx, dy, w, h);
29270
+ ctx.restore();
29271
+ return angle ? null : [x + dx, y + dy, x + dx + w, y + dy + h];
29272
+ };
29273
+
29274
+ CanvasMap.prototype._text = function (ctx, l, c, text, x, y, angle) {
29275
+ var size = layoutOf(l, 'text-size', c, 16);
29276
+ var font = layoutOf(l, 'text-font', c, ['Noto Sans Regular']);
29277
+ var bold = /Bold|Medium|Semibold/i.test(Array.isArray(font) ? font[0] : font);
29278
+ ctx.save();
29279
+ ctx.font = (bold ? '600 ' : '') + size + 'px -apple-system, BlinkMacSystemFont, "Segoe UI", Roboto, "Noto Sans", Arial, sans-serif';
29280
+ var w = ctx.measureText(text).width, h = size * 1.2;
29281
+ var anchor = ANCHOR_SHIFT[layoutOf(l, 'text-anchor', c, 'center')] || ANCHOR_SHIFT.center;
29282
+ var off = layoutOf(l, 'text-offset', c, [0, 0]);
29283
+ var dx = off[0] * size + anchor[0] * w, dy = off[1] * size + anchor[1] * h;
29284
+ ctx.translate(x, y);
29285
+ if (angle) { ctx.rotate(angle); }
29286
+ ctx.textBaseline = 'middle';
29287
+ var halo = paintOf(l, 'text-halo-width', c, 0);
29288
+ if (halo > 0) { ctx.lineWidth = halo * 2; ctx.strokeStyle = paintOf(l, 'text-halo-color', c, '#ffffff'); ctx.lineJoin = 'round'; ctx.strokeText(text, dx, dy + h / 2); }
29289
+ ctx.globalAlpha = paintOf(l, 'text-opacity', c, 1);
29290
+ ctx.fillStyle = paintOf(l, 'text-color', c, '#000000');
29291
+ ctx.fillText(text, dx, dy + h / 2);
29292
+ ctx.restore();
29293
+ return angle ? null : [x + dx, y + dy, x + dx + w, y + dy + h];
29294
+ };
29295
+
29296
+ // A heat map: each point a blurred spot of its weight on an offscreen canvas, then coloured by density.
29297
+ CanvasMap.prototype._drawHeatmap = function (ctx, l, features) {
29298
+ var self = this, zoom = this._zoom, w = this._w, h = this._h;
29299
+ var off = this._heatCanvas = this._heatCanvas || this._doc.createElement('canvas');
29300
+ off.width = w; off.height = h;
29301
+ var hc = off.getContext('2d');
29302
+ if (!hc) { return; }
29303
+ hc.clearRect(0, 0, w, h);
29304
+ var radius = paintOf(l, 'heatmap-radius', { zoom: zoom }, 30), intensity = paintOf(l, 'heatmap-intensity', { zoom: zoom }, 1);
29305
+ features.forEach(function (f) {
29306
+ var c = { zoom: zoom, f: f };
29307
+ if (!f.geometry || !passes(l.filter, c)) { return; }
29308
+ var weight = Math.max(0, Math.min(1, paintOf(l, 'heatmap-weight', c, 1) * intensity * 0.35));
29309
+ self._screen(f.geometry).forEach(function (p) {
29310
+ if (!Array.isArray(p) || typeof p[0] !== 'number' || p[0] < -radius || p[1] < -radius || p[0] > w + radius || p[1] > h + radius) { return; }
29311
+ // A falloff close to the engine's Gaussian kernel of the same radius.
29312
+ var g = hc.createRadialGradient(p[0], p[1], 0, p[0], p[1], radius);
29313
+ g.addColorStop(0, 'rgba(0,0,0,' + weight + ')');
29314
+ g.addColorStop(0.35, 'rgba(0,0,0,' + (weight * 0.45) + ')');
29315
+ g.addColorStop(0.7, 'rgba(0,0,0,' + (weight * 0.08) + ')');
29316
+ g.addColorStop(1, 'rgba(0,0,0,0)');
29317
+ hc.fillStyle = g;
29318
+ hc.fillRect(p[0] - radius, p[1] - radius, radius * 2, radius * 2);
29319
+ });
29320
+ });
29321
+ var img = hc.getImageData(0, 0, w, h), d = img.data;
29322
+ // The colour ramp, sampled once for 256 densities.
29323
+ var ramp = this._ramp(l), opacity = paintOf(l, 'heatmap-opacity', { zoom: zoom }, 1);
29324
+ for (var i = 0; i < d.length; i += 4) {
29325
+ var a = d[i + 3];
29326
+ if (!a) { continue; }
29327
+ var k = a * 4;
29328
+ d[i] = ramp[k]; d[i + 1] = ramp[k + 1]; d[i + 2] = ramp[k + 2]; d[i + 3] = ramp[k + 3] * opacity;
29329
+ }
29330
+ hc.putImageData(img, 0, 0);
29331
+ ctx.save();
29332
+ ctx.setTransform(1, 0, 0, 1, 0, 0);
29333
+ ctx.drawImage(off, 0, 0, w, h, 0, 0, this._canvas.width, this._canvas.height);
29334
+ ctx.restore();
29335
+ };
29336
+
29337
+ CanvasMap.prototype._ramp = function (l) {
29338
+ var expr = l.paint && l.paint['heatmap-color'];
29339
+ var key = JSON.stringify(expr);
29340
+ if (this._rampKey === key && this._rampData) { return this._rampData; }
29341
+ var c = this._doc.createElement('canvas');
29342
+ c.width = 256; c.height = 1;
29343
+ var x = c.getContext('2d');
29344
+ var stops = Array.isArray(expr) && expr[0] === 'interpolate' ? expr.slice(3) : [0, 'rgba(0,0,255,0)', 0.5, 'rgb(0,255,0)', 1, 'rgb(255,0,0)'];
29345
+ var grad = x.createLinearGradient(0, 0, 256, 0);
29346
+ for (var i = 0; i < stops.length; i += 2) { grad.addColorStop(Math.max(0, Math.min(1, stops[i])), stops[i + 1]); }
29347
+ x.fillStyle = grad;
29348
+ x.fillRect(0, 0, 256, 1);
29349
+ this._rampKey = key;
29350
+ this._rampData = x.getImageData(0, 0, 256, 1).data;
29351
+ return this._rampData;
29352
+ };
29353
+
29354
+ // ---- hit tests
29355
+
29356
+ function hits(entry, x0, y0, x1, y1) {
29357
+ var h = entry.hit, cx = (x0 + x1) / 2, cy = (y0 + y1) / 2, pad = Math.max(x1 - x0, y1 - y0) / 2;
29358
+ if (h.kind === 'circle') { return Math.sqrt(Math.pow(h.x - cx, 2) + Math.pow(h.y - cy, 2)) <= h.r + pad; }
29359
+ if (h.kind === 'box') { return h.box[0] <= x1 && h.box[2] >= x0 && h.box[1] <= y1 && h.box[3] >= y0; }
29360
+ if (h.kind === 'line') {
29361
+ var reach = h.width / 2 + Math.max(3, pad);
29362
+ for (var i = 0; i < h.lines.length; i++) {
29363
+ var ln = h.lines[i];
29364
+ for (var j = 1; j < ln.length; j++) { if (segDist(cx, cy, ln[j - 1][0], ln[j - 1][1], ln[j][0], ln[j][1]) <= reach) { return true; } }
29365
+ }
29366
+ return false;
29367
+ }
29368
+ if (h.kind === 'fill') {
29369
+ return h.polys.some(function (rings) {
29370
+ if (!rings.length || !inRing(cx, cy, rings[0])) { return false; }
29371
+ for (var k = 1; k < rings.length; k++) { if (inRing(cx, cy, rings[k])) { return false; } }
29372
+ return true;
29373
+ });
29374
+ }
29375
+ return false;
29376
+ }
29377
+
29378
+ /** Features drawn at a point or in a box, top first: { type, id, properties, geometry, layer: { id }, source }. */
29379
+ CanvasMap.prototype.queryRenderedFeatures = function (at, o) {
29380
+ if (at && !Array.isArray(at) && at.layers) { o = at; at = null; }
29381
+ o = o || {};
29382
+ var x0, y0, x1, y1;
29383
+ if (!at) { x0 = 0; y0 = 0; x1 = this._w; y1 = this._h; }
29384
+ else if (Array.isArray(at) && Array.isArray(at[0])) { x0 = Math.min(at[0][0], at[1][0]); x1 = Math.max(at[0][0], at[1][0]); y0 = Math.min(at[0][1], at[1][1]); y1 = Math.max(at[0][1], at[1][1]); }
29385
+ else { var p = Array.isArray(at) ? { x: at[0], y: at[1] } : at; x0 = x1 = p.x; y0 = y1 = p.y; }
29386
+ var out = [], seen = [];
29387
+ for (var i = this._drawn.length - 1; i >= 0; i--) {
29388
+ var d = this._drawn[i];
29389
+ if (o.layers && o.layers.indexOf(d.layer.id) < 0) { continue; }
29390
+ if (!hits(d, x0, y0, x1, y1)) { continue; }
29391
+ if (seen.indexOf(d) >= 0) { continue; }
29392
+ seen.push(d);
29393
+ out.push({ type: 'Feature', id: d.f.id, properties: d.f.properties || {}, geometry: d.f.geometry, layer: { id: d.layer.id, type: d.layer.type }, source: d.layer.source });
29394
+ }
29395
+ return out;
29396
+ };
29397
+
29398
+ CanvasMap.prototype.querySourceFeatures = function (id, o) {
29399
+ var src = this._sources[id];
29400
+ if (!src || !src._shown) { return []; }
29401
+ var zoom = this._zoom, filter = o && o.filter;
29402
+ return src._shown(zoom).filter(function (f) { return passes(filter, { zoom: zoom, f: f }); });
29403
+ };
29404
+
29405
+ // ---- input: pointer, wheel, touch, keyboard
29406
+
29407
+ CanvasMap.prototype._event = function (type, original, point) {
29408
+ var self = this;
29409
+ var e = {
29410
+ type: type, originalEvent: original, point: point, lngLat: this.unproject(point), target: this, defaultPrevented: false,
29411
+ preventDefault: function () { e.defaultPrevented = true; if (type === 'mousedown' || type === 'touchstart') { self._drag = null; } },
29412
+ };
29413
+ if (original && original.touches) { e.points = Array.prototype.map.call(original.touches, function (t) { return self._point(t); }); }
29414
+ return e;
29415
+ };
29416
+
29417
+ CanvasMap.prototype._point = function (ev) {
29418
+ var r = this._container.getBoundingClientRect();
29419
+ return { x: ev.clientX - r.left, y: ev.clientY - r.top };
29420
+ };
29421
+
29422
+ // A map event to the map's listeners and to the layers' listeners whose features are under the point.
29423
+ CanvasMap.prototype._dispatch = function (type, original, point) {
29424
+ var e = this._event(type, original, point);
29425
+ var self = this;
29426
+ var layerTypes = { click: 1, dblclick: 1, mousedown: 1, mouseup: 1, mousemove: 1, touchstart: 1, touchend: 1, contextmenu: 1 };
29427
+ if (layerTypes[type]) {
29428
+ this._layerEvents.forEach(function (h) {
29429
+ if (h.type !== type) { return; }
29430
+ var features = self.queryRenderedFeatures(point, { layers: [h.layer] });
29431
+ if (!features.length) { return; }
29432
+ var le = self._event(type, original, point);
29433
+ le.features = features;
29434
+ h.fn(le);
29435
+ if (le.defaultPrevented) { e.preventDefault(); }
29436
+ });
29437
+ }
29438
+ if (type === 'mousemove') {
29439
+ // mouseenter / mouseleave per layer.
29440
+ this._layerEvents.forEach(function (h) {
29441
+ if (h.type !== 'mouseenter' && h.type !== 'mouseleave') { return; }
29442
+ var features = self.queryRenderedFeatures(point, { layers: [h.layer] });
29443
+ var inside = features.length > 0;
29444
+ if (inside && !h.inside && h.type === 'mouseenter') { var en = self._event('mouseenter', original, point); en.features = features; h.fn(en); }
29445
+ if (!inside && h.inside && h.type === 'mouseleave') { h.fn(self._event('mouseleave', original, point)); }
29446
+ h.inside = inside;
29447
+ });
29448
+ }
29449
+ (this._events[type] || []).slice().forEach(function (fn) { fn(e); });
29450
+ return e;
29451
+ };
29452
+
29453
+ CanvasMap.prototype._input = function () {
29454
+ var self = this, el = this._canvasContainer, doc = this._doc;
29455
+ var down = null, moved = false, lastClick = 0;
29456
+ var start = function (ev, point) {
29457
+ var e = self._dispatch(ev.touches ? 'touchstart' : 'mousedown', ev, point);
29458
+ moved = false;
29459
+ down = point;
29460
+ self._drag = e.defaultPrevented || !self.dragPan.on ? null : { from: point, center: self.project(self._center) };
29461
+ };
29462
+ el.addEventListener('mousedown', function (ev) {
29463
+ if (ev.button !== 0 || ev.target !== self._canvas) { return; }
29464
+ start(ev, self._point(ev));
29465
+ });
29466
+ doc.addEventListener('mousemove', function (ev) {
29467
+ var point = self._point(ev);
29468
+ if (self._drag) {
29469
+ var d = self._drag;
29470
+ if (!moved && Math.abs(point.x - d.from.x) + Math.abs(point.y - d.from.y) < 3) { return; }
29471
+ if (!moved) { self._fire('movestart', {}); self._fire('dragstart', {}); }
29472
+ moved = true;
29473
+ self._set(self.unproject([d.center.x - (point.x - d.from.x), d.center.y - (point.y - d.from.y)]));
29474
+ self._fire('drag', {});
29475
+ return;
29476
+ }
29477
+ if (down) { moved = moved || Math.abs(point.x - down.x) + Math.abs(point.y - down.y) >= 3; }
29478
+ var inside = point.x >= 0 && point.y >= 0 && point.x <= self._w && point.y <= self._h;
29479
+ if (inside || down) { self._dispatch('mousemove', ev, point); }
29480
+ else if (self._wasInside) { self._dispatch('mouseout', ev, point); }
29481
+ self._wasInside = inside;
29482
+ });
29483
+ doc.addEventListener('mouseup', function (ev) {
29484
+ if (!down) { return; }
29485
+ var point = self._point(ev);
29486
+ var wasDrag = !!self._drag && moved;
29487
+ self._drag = null;
29488
+ self._dispatch('mouseup', ev, point);
29489
+ if (wasDrag) { self._fire('dragend', {}); self._end(false); }
29490
+ else if (!moved && ev.target && (ev.target === self._canvas)) {
29491
+ var now = Date.now();
29492
+ self._dispatch('click', ev, point);
29493
+ if (now - lastClick < 300) {
29494
+ var dbl = self._dispatch('dblclick', ev, point);
29495
+ if (!dbl.defaultPrevented && self.doubleClickZoom.on) { self.easeTo({ zoom: self._zoom + (ev.shiftKey ? -1 : 1), center: self.unproject(point), duration: 250 }); }
29496
+ lastClick = 0;
29497
+ } else { lastClick = now; }
29498
+ }
29499
+ down = null;
29500
+ });
29501
+ el.addEventListener('wheel', function (ev) {
29502
+ if (!self.scrollZoom.on) { return; }
29503
+ ev.preventDefault();
29504
+ var point = self._point(ev);
29505
+ var dz = -ev.deltaY * (ev.deltaMode === 1 ? 0.05 : 0.0025);
29506
+ dz = Math.max(-1, Math.min(1, dz));
29507
+ var before = self.unproject(point);
29508
+ self._set(null, self._zoom + dz);
29509
+ // Keep the place under the pointer where it was.
29510
+ var p = self.project(before), c = self.project(self._center);
29511
+ self._set(self.unproject([c.x + p.x - point.x, c.y + p.y - point.y]));
29512
+ clearTimeout(self._wheelEnd);
29513
+ self._wheelEnd = setTimeout(function () { self._end(true); }, 150);
29514
+ }, { passive: false });
29515
+ // Touch: one finger pans, two fingers pinch.
29516
+ var pinch = null;
29517
+ el.addEventListener('touchstart', function (ev) {
29518
+ if (ev.touches.length === 1) { start(ev, self._point(ev.touches[0])); }
29519
+ else if (ev.touches.length === 2 && self.touchZoomRotate.on) {
29520
+ self._drag = null;
29521
+ var a = self._point(ev.touches[0]), b = self._point(ev.touches[1]);
29522
+ pinch = { d: Math.hypot(a.x - b.x, a.y - b.y), zoom: self._zoom, mid: self.unproject([(a.x + b.x) / 2, (a.y + b.y) / 2]) };
29523
+ }
29524
+ }, { passive: true });
29525
+ el.addEventListener('touchmove', function (ev) {
29526
+ if (pinch && ev.touches.length === 2) {
29527
+ ev.preventDefault();
29528
+ var a = self._point(ev.touches[0]), b = self._point(ev.touches[1]);
29529
+ var d = Math.hypot(a.x - b.x, a.y - b.y), mid = { x: (a.x + b.x) / 2, y: (a.y + b.y) / 2 };
29530
+ self._set(null, pinch.zoom + Math.log2(d / Math.max(1, pinch.d)));
29531
+ var p = self.project(pinch.mid), c = self.project(self._center);
29532
+ self._set(self.unproject([c.x + p.x - mid.x, c.y + p.y - mid.y]));
29533
+ return;
29534
+ }
29535
+ if (ev.touches.length !== 1) { return; }
29536
+ var point = self._point(ev.touches[0]);
29537
+ if (self._drag) {
29538
+ ev.preventDefault();
29539
+ var dr = self._drag;
29540
+ moved = moved || Math.abs(point.x - dr.from.x) + Math.abs(point.y - dr.from.y) >= 3;
29541
+ self._set(self.unproject([dr.center.x - (point.x - dr.from.x), dr.center.y - (point.y - dr.from.y)]));
29542
+ return;
29543
+ }
29544
+ ev.preventDefault();
29545
+ moved = true;
29546
+ self._dispatch('touchmove', ev, point);
29547
+ }, { passive: false });
29548
+ el.addEventListener('touchend', function (ev) {
29549
+ if (pinch && ev.touches.length < 2) { pinch = null; self._end(true); return; }
29550
+ var t = ev.changedTouches[0];
29551
+ var point = t ? self._point(t) : down || { x: 0, y: 0 };
29552
+ var wasDrag = !!self._drag && moved;
29553
+ self._drag = null;
29554
+ self._dispatch('touchend', ev, point);
29555
+ if (wasDrag) { self._end(false); } else if (!moved) { self._dispatch('click', ev, point); }
29556
+ down = null;
29557
+ });
29558
+ this._canvas.addEventListener('keydown', function (ev) {
29559
+ if (!self.keyboard.on) { return; }
29560
+ var k = ev.key, step = 100;
29561
+ if (k === '+' || k === '=') { self.zoomIn(); } else if (k === '-') { self.zoomOut(); }
29562
+ else if (k === 'ArrowLeft') { self.panBy([-step, 0]); } else if (k === 'ArrowRight') { self.panBy([step, 0]); }
29563
+ else if (k === 'ArrowUp') { self.panBy([0, -step]); } else if (k === 'ArrowDown') { self.panBy([0, step]); }
29564
+ else { return; }
29565
+ ev.preventDefault();
29566
+ });
29567
+ };
29568
+
29569
+ // ------------------------------------------------------------------ popups
29570
+
29571
+ function Popup(options) {
29572
+ this.options = Object.assign({ closeButton: true, closeOnClick: true, offset: 0 }, options || {});
29573
+ this._events = {};
29574
+ }
29575
+ Popup.prototype.setLngLat = function (ll) { this._lngLat = toLngLat(ll); this._update(); return this; };
29576
+ Popup.prototype.getLngLat = function () { return this._lngLat ? new LngLat(this._lngLat.lng, this._lngLat.lat) : null; };
29577
+ Popup.prototype._ensure = function (doc) {
29578
+ if (this._el) { return; }
29579
+ var self = this;
29580
+ var el = this._el = doc.createElement('div');
29581
+ el.className = 'maplibregl-popup' + (this.options.className ? ' ' + this.options.className : '');
29582
+ el.style.position = 'absolute'; el.style.left = '0'; el.style.top = '0';
29583
+ var tip = doc.createElement('div'); tip.className = 'maplibregl-popup-tip';
29584
+ var content = this._content = doc.createElement('div'); content.className = 'maplibregl-popup-content';
29585
+ el.appendChild(tip); el.appendChild(content);
29586
+ if (this.options.maxWidth) { el.style.maxWidth = this.options.maxWidth; }
29587
+ if (this.options.closeButton) {
29588
+ var b = doc.createElement('button');
29589
+ b.type = 'button'; b.className = 'maplibregl-popup-close-button'; b.setAttribute('aria-label', 'Close popup'); b.innerHTML = '&#215;';
29590
+ b.addEventListener('click', function () { self.remove(); });
29591
+ this._closeButton = b;
29592
+ }
29593
+ };
29594
+ Popup.prototype.setHTML = function (html) {
29595
+ var doc = (this._map && this._map._doc) || document;
29596
+ this._ensure(doc);
29597
+ this._content.innerHTML = html;
29598
+ if (this._closeButton) { this._content.appendChild(this._closeButton); }
29599
+ this._update();
29600
+ return this;
29601
+ };
29602
+ Popup.prototype.setDOMContent = function (node) {
29603
+ var doc = (this._map && this._map._doc) || node.ownerDocument || document;
29604
+ this._ensure(doc);
29605
+ while (this._content.firstChild) { this._content.removeChild(this._content.firstChild); }
29606
+ this._content.appendChild(node);
29607
+ if (this._closeButton) { this._content.appendChild(this._closeButton); }
29608
+ this._update();
29609
+ return this;
29610
+ };
29611
+ Popup.prototype.setText = function (t) { return this.setHTML(String(t).replace(/[&<>"']/g, function (c) { return '&#' + c.charCodeAt(0) + ';'; })); };
29612
+ Popup.prototype.getElement = function () { return this._el || null; };
29613
+ Popup.prototype.isOpen = function () { return !!this._map; };
29614
+ Popup.prototype.addTo = function (map) {
29615
+ var self = this;
29616
+ this._map = map;
29617
+ this._ensure(map._doc);
29618
+ map.getCanvasContainer().appendChild(this._el);
29619
+ this._onMove = function () { self._update(); };
29620
+ map.on('move', this._onMove);
29621
+ map.on('resize', this._onMove);
29622
+ if (this.options.closeOnClick) {
29623
+ this._onClick = function () { self.remove(); };
29624
+ setTimeout(function () { if (self._map) { map.on('click', self._onClick); } }, 0);
29625
+ }
29626
+ this._update();
29627
+ this._fire('open');
29628
+ return this;
29629
+ };
29630
+ Popup.prototype.remove = function () {
29631
+ var map = this._map;
29632
+ if (!map) { return this; }
29633
+ if (this._el && this._el.parentNode) { this._el.parentNode.removeChild(this._el); }
29634
+ map.off('move', this._onMove);
29635
+ map.off('resize', this._onMove);
29636
+ if (this._onClick) { map.off('click', this._onClick); }
29637
+ this._map = null;
29638
+ this._fire('close');
29639
+ return this;
29640
+ };
29641
+ Popup.prototype.on = function (type, fn) { (this._events[type] = this._events[type] || []).push(fn); return this; };
29642
+ Popup.prototype.off = function (type, fn) { this._events[type] = (this._events[type] || []).filter(function (f) { return f !== fn; }); return this; };
29643
+ Popup.prototype._fire = function (type) { var self = this; (this._events[type] || []).slice().forEach(function (fn) { fn({ type: type, target: self }); }); };
29644
+ Popup.prototype._update = function () {
29645
+ if (!this._map || !this._el || !this._lngLat) { return; }
29646
+ var p = this._map.project(this._lngLat);
29647
+ var anchor = this.options.anchor || (p.y < this._el.offsetHeight + 20 ? 'top' : 'bottom');
29648
+ var off = this.options.offset, o = typeof off === 'number' ? { top: [0, off], bottom: [0, -off], left: [off, 0], right: [-off, 0] }[anchor.split('-')[0]] || [0, 0] : (Array.isArray(off) ? off : (off && off[anchor]) || [0, 0]);
29649
+ var shift = { center: [-50, -50], top: [-50, 0], bottom: [-50, -100], left: [0, -50], right: [-100, -50], 'top-left': [0, 0], 'top-right': [-100, 0], 'bottom-left': [0, -100], 'bottom-right': [-100, -100] }[anchor] || [-50, -100];
29650
+ var cls = this._el.className.replace(/\s*maplibregl-popup-anchor-[a-z-]+/g, '');
29651
+ this._el.className = cls + ' maplibregl-popup-anchor-' + anchor;
29652
+ this._el.style.transform = 'translate(' + shift[0] + '%, ' + shift[1] + '%) translate(' + Math.round(p.x + o[0]) + 'px, ' + Math.round(p.y + o[1]) + 'px)';
29653
+ };
29654
+
29655
+ // ------------------------------------------------------------------ controls (the engine's class names, so its stylesheet applies)
29656
+
29657
+ function NavigationControl(options) { this.options = Object.assign({ showZoom: true, showCompass: true }, options || {}); }
29658
+ NavigationControl.prototype.onAdd = function (map) {
29659
+ var doc = map._doc, el = this._el = doc.createElement('div');
29660
+ el.className = 'maplibregl-ctrl maplibregl-ctrl-group';
29661
+ var button = function (cls, label, fn) {
29662
+ var b = doc.createElement('button');
29663
+ b.type = 'button'; b.className = cls; b.title = label; b.setAttribute('aria-label', label);
29664
+ var icon = doc.createElement('span'); icon.className = 'maplibregl-ctrl-icon'; icon.setAttribute('aria-hidden', 'true');
29665
+ b.appendChild(icon);
29666
+ b.addEventListener('click', fn);
29667
+ el.appendChild(b);
29668
+ };
29669
+ if (this.options.showZoom) {
29670
+ button('maplibregl-ctrl-zoom-in', 'Zoom in', function () { map.zoomIn(); });
29671
+ button('maplibregl-ctrl-zoom-out', 'Zoom out', function () { map.zoomOut(); });
29672
+ }
29673
+ // The map never turns: no compass.
29674
+ return el;
29675
+ };
29676
+ NavigationControl.prototype.onRemove = function () { if (this._el && this._el.parentNode) { this._el.parentNode.removeChild(this._el); } };
29677
+
29678
+ function ScaleControl(options) { this.options = Object.assign({ maxWidth: 100, unit: 'metric' }, options || {}); }
29679
+ ScaleControl.prototype.onAdd = function (map) {
29680
+ var self = this, el = this._el = map._doc.createElement('div');
29681
+ el.className = 'maplibregl-ctrl maplibregl-ctrl-scale';
29682
+ this._map = map;
29683
+ this._update = function () {
29684
+ var y = map._h / 2, a = map.unproject([0, y]), b = map.unproject([self.options.maxWidth, y]);
29685
+ var R = 6371008.8, rad = Math.PI / 180;
29686
+ var m = 2 * R * Math.asin(Math.sqrt(Math.pow(Math.sin((b.lat - a.lat) * rad / 2), 2) + Math.cos(a.lat * rad) * Math.cos(b.lat * rad) * Math.pow(Math.sin((b.lng - a.lng) * rad / 2), 2)));
29687
+ var imperial = self.options.unit === 'imperial', v = imperial ? m * 3.28084 : m, unit = imperial ? 'ft' : 'm';
29688
+ if (imperial && v > 5280) { v /= 5280; unit = 'mi'; } else if (!imperial && v >= 1000) { v /= 1000; unit = 'km'; }
29689
+ var pow = Math.pow(10, Math.floor(Math.log10(v))), d = v / pow, nice = (d >= 10 ? 10 : d >= 5 ? 5 : d >= 3 ? 3 : d >= 2 ? 2 : 1) * pow;
29690
+ el.style.width = Math.round(self.options.maxWidth * nice / v) + 'px';
29691
+ el.textContent = nice + ' ' + unit;
29692
+ };
29693
+ map.on('move', this._update);
29694
+ this._update();
29695
+ return el;
29696
+ };
29697
+ ScaleControl.prototype.onRemove = function () { if (this._map) { this._map.off('move', this._update); } if (this._el && this._el.parentNode) { this._el.parentNode.removeChild(this._el); } };
29698
+
29699
+ function FullscreenControl(options) { this.options = options || {}; }
29700
+ FullscreenControl.prototype.onAdd = function (map) {
29701
+ var doc = map._doc, self = this, el = this._el = doc.createElement('div');
29702
+ el.className = 'maplibregl-ctrl maplibregl-ctrl-group';
29703
+ var b = doc.createElement('button');
29704
+ b.type = 'button'; b.className = 'maplibregl-ctrl-fullscreen'; b.title = 'Enter fullscreen'; b.setAttribute('aria-label', 'Enter fullscreen');
29705
+ var icon = doc.createElement('span'); icon.className = 'maplibregl-ctrl-icon'; icon.setAttribute('aria-hidden', 'true');
29706
+ b.appendChild(icon);
29707
+ var target = this.options.container || map.getContainer();
29708
+ b.addEventListener('click', function () {
29709
+ if (doc.fullscreenElement) { doc.exitFullscreen(); } else if (target.requestFullscreen) { target.requestFullscreen(); }
29710
+ });
29711
+ this._change = function () {
29712
+ var on = doc.fullscreenElement === target;
29713
+ b.className = on ? 'maplibregl-ctrl-shrink' : 'maplibregl-ctrl-fullscreen';
29714
+ b.title = on ? 'Exit fullscreen' : 'Enter fullscreen';
29715
+ setTimeout(function () { map.resize(); }, 50);
29716
+ };
29717
+ doc.addEventListener('fullscreenchange', this._change);
29718
+ el.appendChild(b);
29719
+ self._doc = doc;
29720
+ return el;
29721
+ };
29722
+ FullscreenControl.prototype.onRemove = function () { if (this._doc) { this._doc.removeEventListener('fullscreenchange', this._change); } if (this._el && this._el.parentNode) { this._el.parentNode.removeChild(this._el); } };
29723
+
29724
+ function GeolocateControl(options) { this.options = options || {}; }
29725
+ GeolocateControl.prototype.onAdd = function (map) {
29726
+ var doc = map._doc, el = this._el = doc.createElement('div');
29727
+ el.className = 'maplibregl-ctrl maplibregl-ctrl-group';
29728
+ var b = doc.createElement('button');
29729
+ b.type = 'button'; b.className = 'maplibregl-ctrl-geolocate'; b.title = 'Find my location'; b.setAttribute('aria-label', 'Find my location');
29730
+ var icon = doc.createElement('span'); icon.className = 'maplibregl-ctrl-icon'; icon.setAttribute('aria-hidden', 'true');
29731
+ b.appendChild(icon);
29732
+ var geo = doc.defaultView && doc.defaultView.navigator && doc.defaultView.navigator.geolocation;
29733
+ if (!geo) { b.disabled = true; }
29734
+ b.addEventListener('click', function () {
29735
+ if (!geo) { return; }
29736
+ geo.getCurrentPosition(function (pos) {
29737
+ map.flyTo({ center: [pos.coords.longitude, pos.coords.latitude], zoom: Math.max(map.getZoom(), 15) });
29738
+ map._fire('geolocate', { coords: pos.coords });
29739
+ }, function (err) { map._fire('error', { error: err }); }, { enableHighAccuracy: true, timeout: 10000 });
29740
+ });
29741
+ el.appendChild(b);
29742
+ return el;
29743
+ };
29744
+ GeolocateControl.prototype.onRemove = function () { if (this._el && this._el.parentNode) { this._el.parentNode.removeChild(this._el); } };
29745
+
29746
+ function AttributionControl(options) { this.options = options || {}; }
29747
+ AttributionControl.prototype.onAdd = function (map) {
29748
+ var el = this._el = map._doc.createElement('details');
29749
+ el.className = 'maplibregl-ctrl maplibregl-ctrl-attrib maplibregl-compact';
29750
+ var summary = map._doc.createElement('summary');
29751
+ summary.className = 'maplibregl-ctrl-attrib-button';
29752
+ summary.title = 'Toggle attribution';
29753
+ summary.setAttribute('aria-label', 'Toggle attribution');
29754
+ var inner = this._inner = map._doc.createElement('div');
29755
+ inner.className = 'maplibregl-ctrl-attrib-inner';
29756
+ el.appendChild(summary);
29757
+ el.appendChild(inner);
29758
+ this._map = map;
29759
+ // Open where there is room, as the engine's own control.
29760
+ if (map._w >= 640) { el.open = true; }
29761
+ this._update();
29762
+ return el;
29763
+ };
29764
+ AttributionControl.prototype._update = function () {
29765
+ if (!this._inner || !this._map) { return; }
29766
+ var parts = [this._map._attribution, this.options.customAttribution].filter(Boolean);
29767
+ this._inner.innerHTML = parts.join(' | ');
29768
+ };
29769
+ AttributionControl.prototype.onRemove = function () { if (this._el && this._el.parentNode) { this._el.parentNode.removeChild(this._el); } };
29770
+
29771
+ function ErrorEvent(error) { this.type = 'error'; this.error = error; }
29772
+
29773
+ /** Whether this browser can draw the WebGL map (WebGL 2). */
29774
+ function webgl2Available(doc) {
29775
+ try {
29776
+ var c = (doc || document).createElement('canvas');
29777
+ return !!(c.getContext && c.getContext('webgl2'));
29778
+ } catch (e) { return false; }
29779
+ }
29780
+
29781
+ return {
29782
+ Map: CanvasMap, Popup: Popup, LngLat: LngLat, LngLatBounds: LngLatBounds,
29783
+ NavigationControl: NavigationControl, ScaleControl: ScaleControl, FullscreenControl: FullscreenControl,
29784
+ GeolocateControl: GeolocateControl, AttributionControl: AttributionControl, ErrorEvent: ErrorEvent,
29785
+ addProtocol: addProtocol, removeProtocol: removeProtocol, webgl2Available: webgl2Available,
29786
+ evaluate: evaluate, clusterAt: clusterAt,
29787
+ };
29788
+ });
29789
+
29790
+ return module.exports;
29791
+ }
28328
29792
  function smapCreatePlan() {
28329
29793
  var module = { exports: {} };
28330
29794
  var exports = module.exports;
@@ -30096,12 +31560,12 @@ function smapCreatePlan() {
30096
31560
 
30097
31561
  return module.exports;
30098
31562
  }
30099
- function smapCreateSdk(engine, interop, plan) {
31563
+ function smapCreateSdk(engine, interop, canvas, plan) {
30100
31564
  var module = { exports: {} };
30101
31565
  var exports = module.exports;
30102
31566
  var define;
30103
31567
  var require = function (name) { throw new Error('sMap: unexpected require of ' + name); };
30104
- var self = { maplibregl: engine, smapInterop: interop, smapPlan: plan };
31568
+ var self = { maplibregl: engine, smapInterop: interop, smapCanvas: canvas, smapPlan: plan };
30105
31569
  /*!
30106
31570
  * sMap Web SDK — maps from Superroute's sMap service.
30107
31571
  *
@@ -30115,14 +31579,15 @@ function smapCreateSdk(engine, interop, plan) {
30115
31579
  if (typeof module === 'object' && module.exports) {
30116
31580
  module.exports = factory(root.maplibregl !== undefined ? root.maplibregl : require('maplibre-gl'),
30117
31581
  root.smapInterop !== undefined ? root.smapInterop : require('./smap-interop.js'),
31582
+ root.smapCanvas !== undefined ? root.smapCanvas : (typeof require === 'function' ? require('./smap-canvas.js') : null),
30118
31583
  root.smapPlan !== undefined ? root.smapPlan : (typeof require === 'function' ? require('./smap-plan.js') : null));
30119
31584
  } else {
30120
- root.sMap = factory(root.maplibregl, root.smapInterop, root.smapPlan);
31585
+ root.sMap = factory(root.maplibregl, root.smapInterop, root.smapCanvas, root.smapPlan);
30121
31586
  }
30122
- })(typeof self !== 'undefined' ? self : this, function (engine, interop, plan) {
31587
+ })(typeof self !== 'undefined' ? self : this, function (engine, interop, canvasLib, plan) {
30123
31588
  'use strict';
30124
31589
 
30125
- var VERSION = '1.1.7';
31590
+ var VERSION = '1.2.1';
30126
31591
  var FLAVORS = ['light', 'white', 'grayscale', 'dark', 'black'];
30127
31592
  var BASEMAP_SOURCE = 'basemap';
30128
31593
  var BUILDINGS_LAYER = 'smap-buildings-3d';
@@ -30347,28 +31812,51 @@ function smapCreateSdk(engine, interop, plan) {
30347
31812
  },
30348
31813
  };
30349
31814
  },
30350
- // pinnum|shape|fill|border|borderWidth|size|textColor|text: a pin with its number drawn in, so a pin above covers a
30351
- // pin below completely (used close up, where few pins are in view; further out the number is its own layer).
31815
+ // pinnum|shape|fill|border|borderWidth|size|textColor|badge|text: a pin with its number and its count badge drawn
31816
+ // in, so a pin above covers a pin below completely, number and badge included, as one element of the route map's
31817
+ // pins does. An empty number or badge is left out; the text comes last because it may hold '|'.
30352
31818
  pinnum: function (args, measure) {
30353
31819
  var pin = IMAGE_KINDS.pin(args.slice(0, 5));
30354
- var size = Number(args[4]), color = args[5], text = args.slice(6).join('|');
31820
+ var size = Number(args[4]), color = args[5], badgeText = args[6] || '', text = args.slice(7).join('|');
30355
31821
  var px = 14 * size / 32, font = 'bold ' + px + 'px monospace';
31822
+ var badge = badgeText !== '' ? IMAGE_KINDS.badge([badgeText], measure) : null;
31823
+ var g = markerGeometry(args[0], size);
31824
+ // The badge's centre is where its own layer puts it: g.badge from the tip, i.e. from the head's centre for a
31825
+ // pin (the image's centre), so the image is widened on both sides when the badge reaches past it.
31826
+ var w = pin.width, h = pin.height;
31827
+ if (badge) {
31828
+ var reach = Math.abs(g.badge[0]) + badge.width / 2;
31829
+ w = Math.max(w, Math.ceil(2 * reach));
31830
+ }
30356
31831
  return {
30357
- width: pin.width, height: pin.height,
31832
+ width: w, height: h,
30358
31833
  draw: function (ctx, ratio) {
30359
- pin.draw(ctx, ratio);
30360
- if (text === '') { return; }
30361
31834
  ctx.save();
30362
- ctx.font = font;
30363
- ctx.textAlign = 'center';
30364
- ctx.textBaseline = 'middle';
30365
- ctx.shadowColor = 'rgba(0,0,0,0.5)';
30366
- ctx.shadowOffsetX = ratio;
30367
- ctx.shadowOffsetY = ratio;
30368
- ctx.shadowBlur = 2 * ratio;
30369
- ctx.fillStyle = color;
30370
- ctx.fillText(text, pin.width / 2, pin.height / 2 + 0.5);
31835
+ ctx.translate((w - pin.width) / 2, 0);
31836
+ pin.draw(ctx, ratio);
30371
31837
  ctx.restore();
31838
+ if (text !== '') {
31839
+ ctx.save();
31840
+ ctx.font = font;
31841
+ ctx.textAlign = 'center';
31842
+ ctx.textBaseline = 'middle';
31843
+ ctx.shadowColor = 'rgba(0,0,0,0.5)';
31844
+ ctx.shadowOffsetX = ratio;
31845
+ ctx.shadowOffsetY = ratio;
31846
+ ctx.shadowBlur = 2 * ratio;
31847
+ ctx.fillStyle = color;
31848
+ ctx.fillText(text, w / 2, h / 2 + 0.5);
31849
+ ctx.restore();
31850
+ }
31851
+ if (badge) {
31852
+ // A pin's head is the image's centre and its tip half the image height lower; the badge sits g.badge from
31853
+ // the tip (a circle's centre is the image's centre).
31854
+ var tipY = args[0] === 'pin' ? h / 2 + g.tipToHead : h / 2;
31855
+ ctx.save();
31856
+ ctx.translate(w / 2 + g.badge[0] - badge.width / 2, tipY + g.badge[1] - badge.height / 2);
31857
+ badge.draw(ctx, ratio);
31858
+ ctx.restore();
31859
+ }
30372
31860
  },
30373
31861
  };
30374
31862
  },
@@ -30533,12 +32021,14 @@ function smapCreateSdk(engine, interop, plan) {
30533
32021
  * @param {Object} [options.popup] default popup options of every layer and openPopup (className, maxWidth,
30534
32022
  * minWidth, offset, anchor, closeButton, closeOnClick, focusAfterOpen)
30535
32023
  * @param {string|Node} [options.popupLoading] shown while a popup's content is a pending promise (default: dots)
32024
+ * @param {'auto'|'webgl'|'canvas'} [options.renderer] 'auto' (default): the WebGL map, or the canvas map (raster
32025
+ * tiles, layers drawn in 2D) where the browser has no WebGL 2 (M67)
30536
32026
  * Every other option (center, zoom, pitch, bearing, minZoom, maxZoom, maxBounds, hash, …) goes to the engine.
30537
32027
  */
30538
32028
  function SMap(options) {
30539
32029
  if (!(this instanceof SMap)) { return new SMap(options); }
30540
32030
  options = options || {};
30541
- if (!engine) { throw new Error('sMap: the rendering engine is not loaded'); }
32031
+ if (!engine && !canvasLib) { throw new Error('sMap: the rendering engine is not loaded'); }
30542
32032
  this._base = (options.baseUrl || DEFAULT_BASE).replace(/\/$/, '');
30543
32033
  this._token = options.token || null;
30544
32034
  this._getToken = options.getToken || null;
@@ -30588,9 +32078,16 @@ function smapCreateSdk(engine, interop, plan) {
30588
32078
  this._toolHandlers = [];
30589
32079
 
30590
32080
  var self = this;
32081
+ // The renderer (M67): the WebGL engine, or the canvas map where there is no WebGL 2 (or when asked for).
32082
+ var want = options.renderer || 'auto';
32083
+ // Asked of the page itself; without a page (a server, a test) the WebGL engine is kept.
32084
+ var hasPage = typeof document !== 'undefined' && !!document && typeof document.createElement === 'function';
32085
+ var useCanvas = !!canvasLib && (want === 'canvas' || (want === 'auto' && (!engine || (hasPage && !canvasLib.webgl2Available(document)))));
32086
+ this._lib = useCanvas ? canvasLib : engine;
32087
+ this.renderer = useCanvas ? 'canvas' : 'webgl';
30591
32088
  var engineOptions = {};
30592
32089
  for (var k in options) {
30593
- if (Object.prototype.hasOwnProperty.call(options, k) && ['token', 'getToken', 'apiKey', 'style', 'language', 'baseUrl', 'projection', 'nearest', 'nodes', 'popup', 'popupLoading', 'autoZoom', 'keyboard3D', 'tools'].indexOf(k) < 0) {
32090
+ if (Object.prototype.hasOwnProperty.call(options, k) && ['token', 'getToken', 'apiKey', 'style', 'language', 'baseUrl', 'projection', 'nearest', 'nodes', 'popup', 'popupLoading', 'autoZoom', 'keyboard3D', 'tools', 'renderer'].indexOf(k) < 0) {
30594
32091
  engineOptions[k] = options[k];
30595
32092
  }
30596
32093
  }
@@ -30598,6 +32095,11 @@ function smapCreateSdk(engine, interop, plan) {
30598
32095
  // The page's origin is its identity: no app header is sent from a browser. The key travels in the style URL
30599
32096
  // (the service carries it into the tile URLs) and, for a style given as a URL or an object, as a header.
30600
32097
  engineOptions.transformRequest = function (url) {
32098
+ // Tiles of the canvas map are images: the token rides in the query (sMap reads `token` there too).
32099
+ if (self.renderer === 'canvas') {
32100
+ if (self._token && url.indexOf(self._base) === 0 && !/[?&]token=/.test(url)) { url += (url.indexOf('?') >= 0 ? '&' : '?') + 'token=' + encodeURIComponent(self._token); }
32101
+ return { url: url };
32102
+ }
30601
32103
  if ((self._token || self._apiKey) && url.indexOf(self._base) === 0) {
30602
32104
  var headers = {};
30603
32105
  if (self._token) { headers.Authorization = 'Bearer ' + self._token; }
@@ -30615,8 +32117,17 @@ function smapCreateSdk(engine, interop, plan) {
30615
32117
  options.nearest === false ? Promise.resolve() : nearestNode(this._base, options.nodes).then(function (base) { self._base = base; })
30616
32118
  ]);
30617
32119
  this.ready = start.then(function () {
30618
- engineOptions.style = self._styleUrl();
30619
- self.engine = new engine.Map(engineOptions);
32120
+ engineOptions.style = self._engineStyle();
32121
+ try {
32122
+ self.engine = new self._lib.Map(engineOptions);
32123
+ } catch (error) {
32124
+ // A WebGL context the browser refuses (a blocked GPU, too many maps): the canvas map instead, when allowed.
32125
+ if (self.renderer !== 'webgl' || want !== 'auto' || !canvasLib) { throw error; }
32126
+ self._lib = canvasLib;
32127
+ self.renderer = 'canvas';
32128
+ engineOptions.style = self._engineStyle();
32129
+ self.engine = new canvasLib.Map(engineOptions);
32130
+ }
30620
32131
  deckCompat(self.engine);
30621
32132
  if (self.engine.addControl) {
30622
32133
  var badge = badgeControl();
@@ -30645,6 +32156,20 @@ function smapCreateSdk(engine, interop, plan) {
30645
32156
  else if (style) { this._customStyle = style; this._serverStyle = null; }
30646
32157
  };
30647
32158
 
32159
+ // The style handed to the renderer: the vector style, or for the canvas map sMap's raster tiles of the same scheme.
32160
+ SMap.prototype._engineStyle = function () {
32161
+ if (this.renderer !== 'canvas') { return this._styleUrl(); }
32162
+ if (this._customStyle && typeof this._customStyle === 'object') { return this._customStyle; }
32163
+ var name = this._serverStyle || this._flavor;
32164
+ var win = typeof window !== 'undefined' ? window : {};
32165
+ var tiles = interop.rasterUrl(name, { baseUrl: this._base, lang: this._language, apiKey: this._apiKey, retina: (win.devicePixelRatio || 1) > 1 });
32166
+ return {
32167
+ version: 8,
32168
+ sources: { 'smap-raster': { type: 'raster', tiles: [tiles], tileSize: 256, maxzoom: 19, attribution: '&copy; <a href="https://www.openstreetmap.org/copyright">OpenStreetMap</a>' } },
32169
+ layers: [{ id: 'smap-raster', type: 'raster', source: 'smap-raster' }],
32170
+ };
32171
+ };
32172
+
30648
32173
  SMap.prototype._styleUrl = function () {
30649
32174
  if (this._customStyle) { return this._customStyle; }
30650
32175
  if (this._serverStyle) { return interop.styleUrl(this._serverStyle, { baseUrl: this._base, lang: this._language, apiKey: this._apiKey }); }
@@ -30675,7 +32200,7 @@ function smapCreateSdk(engine, interop, plan) {
30675
32200
  SMap.prototype.setStyle = function (style) {
30676
32201
  this._takeStyle(style);
30677
32202
  this._styleReady = false;
30678
- this.engine.setStyle(this._styleUrl());
32203
+ this.engine.setStyle(this._engineStyle());
30679
32204
  this._styleClass();
30680
32205
  return this;
30681
32206
  };
@@ -30752,7 +32277,7 @@ function smapCreateSdk(engine, interop, plan) {
30752
32277
  var k = POPUP_OPTIONS[i];
30753
32278
  if (k !== 'className' && k !== 'minWidth' && k !== 'autoPan' && o[k] !== undefined) { engineOptions[k] = k === 'maxWidth' ? cssSize(o[k]) : o[k]; }
30754
32279
  }
30755
- var popup = new engine.Popup(engineOptions).setLngLat(lngLat);
32280
+ var popup = new this._lib.Popup(engineOptions).setLngLat(lngLat);
30756
32281
  this._popup = popup;
30757
32282
  var pending = isThenable(content);
30758
32283
  var loading = o.loading !== undefined ? o.loading : (this._popupLoading !== undefined ? this._popupLoading : POPUP_LOADING);
@@ -30804,12 +32329,14 @@ function smapCreateSdk(engine, interop, plan) {
30804
32329
 
30805
32330
  SMap.prototype._reportError = function (error) {
30806
32331
  var m = this.engine;
30807
- if (m && engine.ErrorEvent && m.fire) { m.fire(new engine.ErrorEvent(error)); } else if (typeof console !== 'undefined') { console.error(error); }
32332
+ if (m && this._lib.ErrorEvent && m.fire) { m.fire(new this._lib.ErrorEvent(error)); } else if (typeof console !== 'undefined') { console.error(error); }
30808
32333
  };
30809
32334
 
30810
32335
  // A click on the map: the top feature of the layers with a popup, if any, opens its layer's popup.
30811
32336
  SMap.prototype._popupClick = function (e) {
30812
32337
  var m = this.engine;
32338
+ // The release of a drag is not a click.
32339
+ if (this._dragEndedAt && Date.now() - this._dragEndedAt < 300) { return; }
30813
32340
  var ids = [];
30814
32341
  var byEngineLayer = {};
30815
32342
  for (var i = 0; i < this._order.length; i++) {
@@ -30936,7 +32463,7 @@ function smapCreateSdk(engine, interop, plan) {
30936
32463
  SMap.prototype.setLanguage = function (language) {
30937
32464
  this._language = language;
30938
32465
  // A scheme or a custom style of sMap is served per language; a style of your own keeps its labels.
30939
- if (!this._customStyle) { this._styleReady = false; this.engine.setStyle(this._styleUrl()); }
32466
+ if (!this._customStyle) { this._styleReady = false; this.engine.setStyle(this._engineStyle()); }
30940
32467
  return this;
30941
32468
  };
30942
32469
 
@@ -31051,6 +32578,8 @@ function smapCreateSdk(engine, interop, plan) {
31051
32578
  var def = this._layers[id];
31052
32579
  if (!def) { throw new Error('sMap: no layer ' + id); }
31053
32580
  def.data = toFeatureCollection(data);
32581
+ if (def.kind === 'custom') { this._customData(id, def); return this; }
32582
+ if (def.kind === 'models') { if (this.engine) { this.engine.triggerRepaint(); } return this; }
31054
32583
  if (def.hovered) { this._setHover(id, def, null); }
31055
32584
  var src = this.engine.getSource('smap-' + id);
31056
32585
  if (src) { src.setData(def.data); }
@@ -31062,6 +32591,8 @@ function smapCreateSdk(engine, interop, plan) {
31062
32591
  if (!def) { return this; }
31063
32592
  def.hidden = !visible;
31064
32593
  var m = this.engine;
32594
+ if (def.kind === 'custom') { if (!visible && this._tooltipFor && this._tooltipFor.id === id) { this._hideTooltip(); } this._layoutMarkers(); return this; }
32595
+ if (def.clusterSet) { this._layoutMarkers(); }
31065
32596
  if (!m) { return this; }
31066
32597
  def.engineLayers.forEach(function (l) { if (m.getLayer(l)) { m.setLayoutProperty(l, 'visibility', visible ? 'visible' : 'none'); } });
31067
32598
  return this;
@@ -31094,7 +32625,7 @@ function smapCreateSdk(engine, interop, plan) {
31094
32625
  SMap.prototype.fitLayer = function (id, options) {
31095
32626
  var def = this._layers[id];
31096
32627
  if (!def || !def.data.features.length) { return this; }
31097
- var b = new engine.LngLatBounds();
32628
+ var b = new this._lib.LngLatBounds();
31098
32629
  def.data.features.forEach(function extend(f) {
31099
32630
  (function walk(c) { if (typeof c[0] === 'number') { b.extend(c); } else { c.forEach(walk); } })(f.geometry.coordinates);
31100
32631
  });
@@ -31108,6 +32639,611 @@ function smapCreateSdk(engine, interop, plan) {
31108
32639
  SMap.prototype.flyTo = function (o) { this.engine.flyTo(o); return this; };
31109
32640
  SMap.prototype.remove = function () { clearTimeout(this._refreshTimer); if (this.engine) { this.engine.remove(); } };
31110
32641
 
32642
+ // ------------------------------------------------------------------ custom markers (G1), dragging (G2), tooltips (G5)
32643
+
32644
+ // A value that may differ per feature, read in JavaScript (custom markers, tooltips): a constant, a function of the
32645
+ // properties, or { property, default }. Engine expressions (arrays) are not read here and give the fallback.
32646
+ function plainValue(v, props, feature, fallback) {
32647
+ if (v === undefined || v === null) { return fallback; }
32648
+ if (typeof v === 'function') { var r = v(props || {}, feature); return r === undefined ? fallback : r; }
32649
+ if (Array.isArray(v)) { return fallback; }
32650
+ if (typeof v === 'object' && v.property) {
32651
+ var x = props ? props[v.property] : undefined;
32652
+ return x === undefined || x === null ? (v['default'] !== undefined ? v['default'] : fallback) : x;
32653
+ }
32654
+ return v;
32655
+ }
32656
+
32657
+ // Where an element's anchor sits, as the share of its own width and height to move it back by (CSS translate).
32658
+ var ANCHORS = {
32659
+ center: [-50, -50], top: [-50, 0], bottom: [-50, -100], left: [0, -50], right: [-100, -50],
32660
+ 'top-left': [0, 0], 'top-right': [-100, 0], 'bottom-left': [0, -100], 'bottom-right': [-100, -100],
32661
+ };
32662
+ // Pixels outside the map an element is still laid out in, so one entering the view is already there.
32663
+ var MARKER_MARGIN = 64;
32664
+ var DRAG_THRESHOLD = 3;
32665
+
32666
+ function featureKey(def, f, i) {
32667
+ var idp = def.o.idProperty;
32668
+ if (idp && f.properties && f.properties[idp] !== undefined && f.properties[idp] !== null) { return String(f.properties[idp]); }
32669
+ if (f.id !== undefined && f.id !== null) { return String(f.id); }
32670
+ return '#' + i;
32671
+ }
32672
+
32673
+ function pointOf(f) {
32674
+ var g = f && f.geometry;
32675
+ return g && g.type === 'Point' && Array.isArray(g.coordinates) && typeof g.coordinates[0] === 'number' ? g.coordinates : null;
32676
+ }
32677
+
32678
+ function offsetOf(v) {
32679
+ if (Array.isArray(v)) { return [+v[0] || 0, +v[1] || 0]; }
32680
+ if (typeof v === 'number') { return [0, -v]; }
32681
+ return [0, 0];
32682
+ }
32683
+
32684
+ // A feature's properties without its position (data given as {lng, lat, …} carries the position in them too), so a
32685
+ // marker that only moved is not rendered again.
32686
+ var POSITION_KEYS = { lng: 1, lat: 1, lon: 1, longitude: 1, latitude: 1, coordinates: 1 };
32687
+ function propsSignature(f) {
32688
+ var p = (f && f.properties) || {}, out = {};
32689
+ Object.keys(p).forEach(function (k) { if (!POSITION_KEYS[k]) { out[k] = p[k]; } });
32690
+ return JSON.stringify(out);
32691
+ }
32692
+
32693
+ /** A copy of a feature collection with one feature's point moved (the caller's own objects are never changed). */
32694
+ function movedCollection(fc, index, lngLat) {
32695
+ var features = fc.features.slice();
32696
+ var f = features[index];
32697
+ features[index] = Object.assign({}, f, { geometry: { type: 'Point', coordinates: [lngLat[0], lngLat[1]] } });
32698
+ return { type: 'FeatureCollection', features: features };
32699
+ }
32700
+
32701
+ /**
32702
+ * Custom markers: the caller's own element at each point — any HTML, laid out above the map's drawn layers. One
32703
+ * element per feature, made the first time the feature comes into view and moved while the map moves; features out
32704
+ * of view are not laid out, so thousands stay smooth.
32705
+ * @param {string} id
32706
+ * @param {Object|Array} data GeoJSON points, or an array of {lng, lat, …properties}
32707
+ * @param {Object} o
32708
+ * render(properties, feature) → an element or trusted HTML (inserted as is, never sanitized); required
32709
+ * anchor: 'center' (default), 'top', 'bottom', 'left', 'right', 'top-left', 'top-right', 'bottom-left', 'bottom-right'
32710
+ * offset: [x, y] pixels; className; opacity, zIndex (constants, functions of the properties or { property });
32711
+ * idProperty (the property naming each feature, else the feature's id, else its place in the data);
32712
+ * riseOnHover (the element under the pointer comes to the front); minzoom; maxzoom;
32713
+ * onClick(feature, event); popup (as on addPoints); tooltip, tooltipOptions (see addPoints);
32714
+ * draggable (true, or per feature), onDragStart / onDrag / onDragEnd(feature, { lngLat, point, originalEvent })
32715
+ */
32716
+ SMap.prototype.addCustomMarkers = function (id, data, o) {
32717
+ o = o || {};
32718
+ if (typeof o.render !== 'function') { throw new Error('sMap: custom markers need render(properties, feature)'); }
32719
+ if (o.anchor !== undefined && !ANCHORS[o.anchor]) { throw new Error('sMap: unknown anchor "' + o.anchor + '"'); }
32720
+ this._define(id, { kind: 'custom', data: toFeatureCollection(data), o: o });
32721
+ return this;
32722
+ };
32723
+
32724
+ /**
32725
+ * The element of one custom marker (made now if it was not in view yet), or null.
32726
+ * @param {string} id the layer
32727
+ * @param {string|number} key the feature's idProperty value, its id, or '#<index>'
32728
+ */
32729
+ SMap.prototype.getMarker = function (id, key) {
32730
+ var def = this._layers[id];
32731
+ if (!def || def.kind !== 'custom' || !def.custom) { return null; }
32732
+ var item = def.custom.byKey[String(key)];
32733
+ if (!item) { return null; }
32734
+ if (!item.el) { this._renderMarker(id, def, item); }
32735
+ return item.el;
32736
+ };
32737
+
32738
+ SMap.prototype._markerOverlay = function () {
32739
+ if (this._overlay && this._overlay.parentNode) { return this._overlay; }
32740
+ var m = this.engine;
32741
+ var host = m.getCanvasContainer ? m.getCanvasContainer() : m.getContainer();
32742
+ var doc = host.ownerDocument;
32743
+ var overlay = doc.createElement('div');
32744
+ overlay.className = 'smap-markers';
32745
+ // First in the canvas container after the canvas, so the engine's popups (added after it) stay on top.
32746
+ var canvas = m.getCanvas ? m.getCanvas() : null;
32747
+ if (canvas && canvas.parentNode === host) { host.insertBefore(overlay, canvas.nextSibling); } else { host.appendChild(overlay); }
32748
+ this._overlay = overlay;
32749
+ var self = this;
32750
+ if (!this._overlayBound) {
32751
+ this._overlayBound = true;
32752
+ var frame = null;
32753
+ var schedule = function () {
32754
+ if (frame !== null) { return; }
32755
+ var raf = typeof requestAnimationFrame === 'function' ? requestAnimationFrame : function (fn) { return setTimeout(fn, 16); };
32756
+ frame = raf(function () { frame = null; self._layoutMarkers(); });
32757
+ };
32758
+ this._scheduleLayout = schedule;
32759
+ m.on('move', function () { self._layoutMarkers(); });
32760
+ m.on('resize', schedule);
32761
+ m.on('zoomend', schedule);
32762
+ }
32763
+ return overlay;
32764
+ };
32765
+
32766
+ SMap.prototype._addCustom = function (id, def) {
32767
+ this._dropCustom(id, def);
32768
+ var items = [];
32769
+ var byKey = {};
32770
+ def.data.features.forEach(function (f, i) {
32771
+ var at = pointOf(f);
32772
+ if (!at) { return; }
32773
+ var item = { key: featureKey(def, f, i), index: i, f: f, el: null, shown: false, x: NaN, y: NaN, sig: null };
32774
+ items.push(item);
32775
+ byKey[item.key] = item;
32776
+ });
32777
+ def.custom = { items: items, byKey: byKey };
32778
+ this._markerOverlay();
32779
+ this._layoutMarkers();
32780
+ };
32781
+
32782
+ SMap.prototype._dropCustom = function (id, def) {
32783
+ var c = def.custom;
32784
+ if (!c) { return; }
32785
+ c.items.forEach(function (item) { if (item.el && item.el.parentNode) { item.el.parentNode.removeChild(item.el); } });
32786
+ def.custom = null;
32787
+ if (this._tooltipFor && this._tooltipFor.id === id) { this._hideTooltip(); }
32788
+ };
32789
+
32790
+ // New data for a custom marker layer: an element whose feature (by key) is still there is kept — moved when its point
32791
+ // moved, made again when its properties changed — so a marker being dragged or with its popup open stays the same.
32792
+ SMap.prototype._customData = function (id, def) {
32793
+ var old = def.custom;
32794
+ if (!old || !this.engine) { if (this.engine && this._styleReady) { this._addCustom(id, def); } return; }
32795
+ var items = [];
32796
+ var byKey = {};
32797
+ def.data.features.forEach(function (f, i) {
32798
+ if (!pointOf(f)) { return; }
32799
+ var key = featureKey(def, f, i);
32800
+ var item = old.byKey[key];
32801
+ if (item) {
32802
+ delete old.byKey[key];
32803
+ if (item.el && propsSignature(item.f) !== propsSignature(f)) { item.sig = null; }
32804
+ item.f = f;
32805
+ item.index = i;
32806
+ item.x = NaN;
32807
+ } else {
32808
+ item = { key: key, index: i, f: f, el: null, shown: false, x: NaN, y: NaN, sig: null };
32809
+ }
32810
+ items.push(item);
32811
+ byKey[key] = item;
32812
+ });
32813
+ Object.keys(old.byKey).forEach(function (k) { var gone = old.byKey[k]; if (gone.el && gone.el.parentNode) { gone.el.parentNode.removeChild(gone.el); } });
32814
+ def.custom = { items: items, byKey: byKey };
32815
+ this._layoutMarkers();
32816
+ };
32817
+
32818
+ SMap.prototype._renderMarker = function (id, def, item) {
32819
+ var self = this, o = def.o, doc = this._markerOverlay().ownerDocument;
32820
+ var el = item.el;
32821
+ if (!el) {
32822
+ el = doc.createElement('div');
32823
+ el.setAttribute('data-smap-layer', id);
32824
+ el.setAttribute('data-smap-key', item.key);
32825
+ item.el = el;
32826
+ this._bindMarker(id, def, item);
32827
+ }
32828
+ var props = item.f.properties || {};
32829
+ var content = o.render(props, item.f);
32830
+ while (el.firstChild) { el.removeChild(el.firstChild); }
32831
+ if (isElement(content)) { el.appendChild(content); } else if (content !== undefined && content !== null) { el.innerHTML = String(content); }
32832
+ el.className = 'smap-marker' + (o.className ? ' ' + o.className : '') + (o.onClick || o.popup || o.draggable || o.tooltip || o.riseOnHover ? ' smap-marker-interactive' : '');
32833
+ var opacity = plainValue(o.opacity, props, item.f, 1);
32834
+ el.style.opacity = opacity === 1 ? '' : String(opacity);
32835
+ item.z = +plainValue(o.zIndex, props, item.f, 0) || 0;
32836
+ item.sig = true;
32837
+ return el;
32838
+ };
32839
+
32840
+ // The anchor and offset of a layer's markers as a CSS transform tail.
32841
+ function anchorTransform(o) {
32842
+ var a = ANCHORS[o.anchor || 'center'], off = offsetOf(o.offset);
32843
+ return ' translate(' + a[0] + '%, ' + a[1] + '%)' + (off[0] || off[1] ? ' translate(' + off[0] + 'px, ' + off[1] + 'px)' : '');
32844
+ }
32845
+
32846
+ // Places every custom marker in view (and takes the ones that left the view out of the page).
32847
+ SMap.prototype._layoutMarkers = function () {
32848
+ var m = this.engine;
32849
+ if (!m || !this._overlay) { return; }
32850
+ var host = this._overlay;
32851
+ var w = host.clientWidth || (m.getContainer && m.getContainer().clientWidth) || 0;
32852
+ var h = host.clientHeight || (m.getContainer && m.getContainer().clientHeight) || 0;
32853
+ var zoom = m.getZoom ? m.getZoom() : 0;
32854
+ var rank = 0;
32855
+ for (var n = 0; n < this._order.length; n++) {
32856
+ var id = this._order[n], layer = this._layers[id];
32857
+ // A custom marker layer, or the HTML clusters of a point layer (cluster.html / cluster.ring).
32858
+ var def = layer.kind === 'custom' ? layer : layer.clusterSet;
32859
+ if (!def || !def.custom) { continue; }
32860
+ rank += 1;
32861
+ var o = def.o;
32862
+ var inRange = !layer.hidden && (o.minzoom === undefined || zoom >= o.minzoom) && (o.maxzoom === undefined || zoom < o.maxzoom);
32863
+ var tail = anchorTransform(o);
32864
+ var items = def.custom.items;
32865
+ for (var i = 0; i < items.length; i++) {
32866
+ var item = items[i];
32867
+ var at = item.dragAt || pointOf(item.f);
32868
+ var p = inRange && at ? m.project(at) : null;
32869
+ var visible = !!p && p.x >= -MARKER_MARGIN && p.y >= -MARKER_MARGIN && p.x <= w + MARKER_MARGIN && p.y <= h + MARKER_MARGIN;
32870
+ if (!visible) {
32871
+ if (item.shown && item.el && item.el.parentNode) { item.el.parentNode.removeChild(item.el); }
32872
+ item.shown = false;
32873
+ continue;
32874
+ }
32875
+ if (!item.el || !item.sig) { this._renderMarker(id, def, item); }
32876
+ var x = Math.round(p.x * 10) / 10, y = Math.round(p.y * 10) / 10;
32877
+ if (x !== item.x || y !== item.y) {
32878
+ item.el.style.transform = 'translate(' + x + 'px, ' + y + 'px)' + tail;
32879
+ item.x = x; item.y = y;
32880
+ }
32881
+ var z = rank * 100000 + (item.raised ? 99999 : Math.max(-99999, Math.min(99998, item.z)));
32882
+ if (item.zSet !== z) { item.el.style.zIndex = String(z); item.zSet = z; }
32883
+ if (!item.shown || item.el.parentNode !== host) { host.appendChild(item.el); item.shown = true; }
32884
+ }
32885
+ }
32886
+ };
32887
+
32888
+ // Click, popup, hover raise, tooltip and dragging of one custom marker.
32889
+ SMap.prototype._bindMarker = function (id, def, item) {
32890
+ var self = this, el = item.el;
32891
+ var o = function () { return def.o; };
32892
+ // The click a drag's release makes is no tap: stopped on the way down, before anything inside the marker (the
32893
+ // app's own buttons, a framework listening on its own element) sees it.
32894
+ el.addEventListener('click', function (e) {
32895
+ if (self._dragEndedAt && Date.now() - self._dragEndedAt < 300) { e.stopPropagation(); if (e.preventDefault) { e.preventDefault(); } }
32896
+ }, true);
32897
+ el.addEventListener('click', function (e) {
32898
+ if (self._dragEndedAt && Date.now() - self._dragEndedAt < 300) { e.stopPropagation(); return; }
32899
+ var lo = o();
32900
+ if (!lo.onClick && !lo.popup) { return; }
32901
+ e.stopPropagation();
32902
+ if (lo.onClick) { lo.onClick(item.f, { originalEvent: e, lngLat: pointOf(item.f) }); }
32903
+ if (lo.popup) { self._markerPopup(id, def, item); }
32904
+ });
32905
+ el.addEventListener('mouseenter', function (e) {
32906
+ var lo = o();
32907
+ if (lo.riseOnHover) { item.raised = true; self._layoutMarkers(); }
32908
+ if (lo.tooltip) { self._showTooltip(id, def, item.f, { element: el }); }
32909
+ });
32910
+ el.addEventListener('mouseleave', function () {
32911
+ if (item.raised) { item.raised = false; self._layoutMarkers(); }
32912
+ if (self._tooltipFor && self._tooltipFor.f === item.f) { self._hideTooltip(); }
32913
+ });
32914
+ var start = function (e) {
32915
+ var lo = o();
32916
+ if (!plainValue(lo.draggable, item.f.properties || {}, item.f, false)) { return; }
32917
+ if (e.button !== undefined && e.button !== 0) { return; }
32918
+ self._startMarkerDrag(id, item, e);
32919
+ };
32920
+ if (typeof el.addEventListener === 'function') {
32921
+ el.addEventListener(typeof window !== 'undefined' && window.PointerEvent ? 'pointerdown' : 'mousedown', start);
32922
+ }
32923
+ };
32924
+
32925
+ SMap.prototype._markerPopup = function (id, def, item) {
32926
+ var o = def.o, fn = def.popupFn || o.popup, content;
32927
+ try { content = fn(item.f.properties || {}, item.f); } catch (error) { this._reportError(error); return; }
32928
+ var options = Object.assign({}, o.popupOptions || {});
32929
+ if (options.offset === undefined && this._popupDefaults.offset === undefined && item.el) {
32930
+ // Above the element as it is drawn: from its anchor to its top edge.
32931
+ var hgt = item.el.offsetHeight || 0, a = ANCHORS[o.anchor || 'center'];
32932
+ options.offset = Math.round(hgt * (-a[1] / 100) - offsetOf(o.offset)[1] + 4);
32933
+ }
32934
+ if (options.anchor === undefined && this._popupDefaults.anchor === undefined) { options.anchor = 'bottom'; }
32935
+ this.openPopup(pointOf(item.f), content, options);
32936
+ };
32937
+
32938
+ // Dragging a custom marker: it follows the pointer from the first move of DRAG_THRESHOLD pixels; the map does not
32939
+ // pan meanwhile. Its layer's data then holds the new position (a copy: the caller's objects are not changed).
32940
+ SMap.prototype._startMarkerDrag = function (id, item, e) {
32941
+ var self = this, m = this.engine, el = item.el;
32942
+ var doc = el.ownerDocument, win = doc.defaultView || {};
32943
+ var box = m.getContainer().getBoundingClientRect();
32944
+ var p0 = m.project(pointOf(item.f));
32945
+ var grab = { x: e.clientX - box.left - p0.x, y: e.clientY - box.top - p0.y };
32946
+ var sx = e.clientX, sy = e.clientY, dragging = false;
32947
+ // The map must not pan under a marker that can be dragged: off from the press, back on at the release.
32948
+ var panWasOn = !!(m.dragPan && m.dragPan.isEnabled && m.dragPan.isEnabled());
32949
+ if (panWasOn) { m.dragPan.disable(); }
32950
+ var lngLatAt = function (ev) {
32951
+ var r = m.getContainer().getBoundingClientRect();
32952
+ var pt = { x: ev.clientX - r.left - grab.x, y: ev.clientY - r.top - grab.y };
32953
+ var ll = m.unproject([pt.x, pt.y]);
32954
+ return { lngLat: [ll.lng, ll.lat], point: pt };
32955
+ };
32956
+ var evt = function (ev, at) { return { lngLat: at.lngLat, point: at.point, originalEvent: ev }; };
32957
+ var move = function (ev) {
32958
+ if (!dragging) {
32959
+ if (Math.abs(ev.clientX - sx) < DRAG_THRESHOLD && Math.abs(ev.clientY - sy) < DRAG_THRESHOLD) { return; }
32960
+ dragging = true;
32961
+ el.classList.add('smap-marker-dragging');
32962
+ item.raised = true;
32963
+ self._hideTooltip();
32964
+ var o0 = self._layers[id].o;
32965
+ if (o0.onDragStart) { o0.onDragStart(item.f, evt(ev, lngLatAt(ev))); }
32966
+ }
32967
+ if (ev.preventDefault) { ev.preventDefault(); }
32968
+ var at = lngLatAt(ev);
32969
+ item.dragAt = at.lngLat;
32970
+ self._layoutMarkers();
32971
+ var o1 = self._layers[id] && self._layers[id].o;
32972
+ if (o1 && o1.onDrag) { o1.onDrag(item.f, evt(ev, at)); }
32973
+ };
32974
+ var up = function (ev) {
32975
+ doc.removeEventListener(upType, up);
32976
+ doc.removeEventListener(moveType, move);
32977
+ if (panWasOn) { m.dragPan.enable(); }
32978
+ if (!dragging) { return; }
32979
+ var at = lngLatAt(ev);
32980
+ item.dragAt = null;
32981
+ item.raised = false;
32982
+ el.classList.remove('smap-marker-dragging');
32983
+ self._dragEndedAt = Date.now();
32984
+ var def = self._layers[id];
32985
+ if (!def) { return; }
32986
+ def.data = movedCollection(def.data, item.index, at.lngLat);
32987
+ item.f = def.data.features[item.index];
32988
+ self._layoutMarkers();
32989
+ if (def.o.onDragEnd) { def.o.onDragEnd(item.f, evt(ev, at)); }
32990
+ };
32991
+ var pointer = !!win.PointerEvent && e.type === 'pointerdown';
32992
+ var moveType = pointer ? 'pointermove' : 'mousemove';
32993
+ var upType = pointer ? 'pointerup' : 'mouseup';
32994
+ doc.addEventListener(moveType, move);
32995
+ doc.addEventListener(upType, up);
32996
+ if (e.stopPropagation) { e.stopPropagation(); }
32997
+ };
32998
+
32999
+ // Dragging a drawn point (addPoints with draggable): the point is taken out of its layer and drawn in a copy of the
33000
+ // layer's own look that follows the pointer, then put back at the new position. Two data updates per drag, whatever
33001
+ // the size of the layer.
33002
+ SMap.prototype._dragPoints = function (id, def, main) {
33003
+ var self = this, m = this.engine;
33004
+ var begin = function (e) {
33005
+ var f = e.features && e.features[0];
33006
+ if (!f || def.hidden) { return; }
33007
+ var index = self._featureIndex(def, f);
33008
+ if (index < 0) { return; }
33009
+ var original = def.data.features[index];
33010
+ if (!plainValue(def.o.draggable, original.properties || {}, original, false)) { return; }
33011
+ if (e.originalEvent && e.originalEvent.button !== undefined && e.originalEvent.button !== 0) { return; }
33012
+ e.preventDefault();
33013
+ var start = e.point, dragging = false, ghost = null;
33014
+ var at = function (ev) { return { lngLat: [ev.lngLat.lng, ev.lngLat.lat], point: { x: ev.point.x, y: ev.point.y }, originalEvent: ev.originalEvent }; };
33015
+ var move = function (ev) {
33016
+ if (!dragging) {
33017
+ if (Math.abs(ev.point.x - start.x) < DRAG_THRESHOLD && Math.abs(ev.point.y - start.y) < DRAG_THRESHOLD) { return; }
33018
+ dragging = true;
33019
+ if (m.dragPan && m.dragPan.disable) { m.dragPan.disable(); }
33020
+ ghost = self._dragGhost(id, def);
33021
+ var without = def.data.features.slice();
33022
+ without.splice(index, 1);
33023
+ var src = m.getSource('smap-' + id);
33024
+ if (src) { src.setData({ type: 'FeatureCollection', features: without }); }
33025
+ if (def.hovered) { self._setHover(id, def, null); }
33026
+ self._hideTooltip();
33027
+ if (def.o.onDragStart) { def.o.onDragStart(original, at(ev)); }
33028
+ }
33029
+ var a = at(ev);
33030
+ if (ghost) { ghost.setData({ type: 'FeatureCollection', features: [Object.assign({}, original, { geometry: { type: 'Point', coordinates: a.lngLat } })] }); }
33031
+ if (def.o.onDrag) { def.o.onDrag(original, a); }
33032
+ };
33033
+ var end = function (ev) {
33034
+ m.off('mousemove', move); m.off('touchmove', move);
33035
+ m.off('mouseup', end); m.off('touchend', end);
33036
+ if (!dragging) { return; }
33037
+ if (m.dragPan && m.dragPan.enable) { m.dragPan.enable(); }
33038
+ self._dropGhost(id);
33039
+ self._dragEndedAt = Date.now();
33040
+ var a = at(ev);
33041
+ def.data = movedCollection(def.data, index, a.lngLat);
33042
+ var src = m.getSource('smap-' + id);
33043
+ if (src) { src.setData(def.data); }
33044
+ if (def.o.onDragEnd) { def.o.onDragEnd(def.data.features[index], a); }
33045
+ };
33046
+ m.on('mousemove', move); m.on('touchmove', move);
33047
+ m.on('mouseup', end); m.on('touchend', end);
33048
+ };
33049
+ this._listen(id, 'mousedown', main, begin);
33050
+ this._listen(id, 'touchstart', main, begin);
33051
+ };
33052
+
33053
+ // The index in a layer's data of a feature the engine answered (by idProperty, else by the generated id).
33054
+ SMap.prototype._featureIndex = function (def, f) {
33055
+ var feats = def.data.features, idp = def.o.idProperty;
33056
+ if (idp) {
33057
+ var want = f.properties ? f.properties[idp] : undefined;
33058
+ for (var i = 0; i < feats.length; i++) { if (feats[i].properties && feats[i].properties[idp] === want) { return i; } }
33059
+ return -1;
33060
+ }
33061
+ return typeof f.id === 'number' && f.id >= 0 && f.id < feats.length ? f.id : -1;
33062
+ };
33063
+
33064
+ // A copy of a layer's engine layers drawing from a one-feature source on top of the map: the point being dragged.
33065
+ SMap.prototype._dragGhost = function (id, def) {
33066
+ var m = this.engine, src = 'smap-' + id, ghostSrc = src + '-drag';
33067
+ this._dropGhost(id);
33068
+ m.addSource(ghostSrc, { type: 'geojson', data: { type: 'FeatureCollection', features: [] } });
33069
+ var st = m.getStyle ? m.getStyle() : null;
33070
+ var ids = [];
33071
+ (st && st.layers ? st.layers : []).forEach(function (l) {
33072
+ if (l.source !== src || def.engineLayers.indexOf(l.id) < 0 || /-(clusters|count)$/.test(l.id)) { return; }
33073
+ var copy = JSON.parse(JSON.stringify(l));
33074
+ copy.id = l.id + '-drag';
33075
+ copy.source = ghostSrc;
33076
+ delete copy.minzoom; delete copy.maxzoom;
33077
+ copy.layout = Object.assign({}, copy.layout || {}, { visibility: 'visible' });
33078
+ m.addLayer(copy);
33079
+ ids.push(copy.id);
33080
+ });
33081
+ this._ghost = { id: id, source: ghostSrc, layers: ids };
33082
+ return m.getSource(ghostSrc);
33083
+ };
33084
+
33085
+ SMap.prototype._dropGhost = function (id) {
33086
+ var g = this._ghost, m = this.engine;
33087
+ if (!g || (id && g.id !== id)) { return; }
33088
+ g.layers.forEach(function (l) { if (m.getLayer(l)) { m.removeLayer(l); } });
33089
+ if (m.getSource(g.source)) { m.removeSource(g.source); }
33090
+ this._ghost = null;
33091
+ };
33092
+
33093
+ // ---- tooltips (G5)
33094
+
33095
+ /**
33096
+ * The map's one tooltip: shown while the pointer is over a feature of a layer with `tooltip`, beside the point (or
33097
+ * the custom marker), or at the pointer on lines and areas. `tooltipOptions`: direction ('top' default, 'bottom',
33098
+ * 'left', 'right'), offset ([x, y] pixels), className.
33099
+ */
33100
+ SMap.prototype._showTooltip = function (id, def, f, at) {
33101
+ var o = def.o, content;
33102
+ var fn = typeof o.tooltip === 'string' ? (def.tooltipFn = def.tooltipFn || popupTemplate(o.tooltip)) : o.tooltip;
33103
+ try { content = fn(f.properties || {}, f); } catch (error) { this._reportError(error); return; }
33104
+ if (content === undefined || content === null || content === '') { this._hideTooltip(); return; }
33105
+ var m = this.engine, overlay = this._markerOverlay(), doc = overlay.ownerDocument;
33106
+ var tip = this._tooltip;
33107
+ if (!tip || tip.parentNode !== overlay) {
33108
+ tip = this._tooltip = doc.createElement('div');
33109
+ overlay.appendChild(tip);
33110
+ }
33111
+ var to = o.tooltipOptions || {};
33112
+ var dir = ['top', 'bottom', 'left', 'right'].indexOf(to.direction) >= 0 ? to.direction : 'top';
33113
+ tip.className = 'smap-tooltip smap-tooltip-' + dir + (to.className ? ' ' + to.className : '');
33114
+ while (tip.firstChild) { tip.removeChild(tip.firstChild); }
33115
+ if (isElement(content)) { tip.appendChild(content); } else { tip.innerHTML = String(content); }
33116
+ var x, y, gap = 6;
33117
+ if (at.element) {
33118
+ var hb = overlay.getBoundingClientRect(), eb = at.element.getBoundingClientRect();
33119
+ x = eb.left - hb.left + eb.width / 2; y = eb.top - hb.top + eb.height / 2;
33120
+ if (dir === 'top') { y = eb.top - hb.top; } else if (dir === 'bottom') { y = eb.bottom - hb.top; }
33121
+ else if (dir === 'left') { x = eb.left - hb.left; } else { x = eb.right - hb.left; }
33122
+ } else {
33123
+ var p = at.point || m.project(at.lngLat);
33124
+ x = p.x; y = p.y;
33125
+ gap = at.gap !== undefined ? at.gap : 10;
33126
+ }
33127
+ var off = offsetOf(to.offset);
33128
+ var shift = { top: [-50, -100, 0, -gap], bottom: [-50, 0, 0, gap], left: [-100, -50, -gap, 0], right: [0, -50, gap, 0] }[dir];
33129
+ tip.style.transform = 'translate(' + Math.round(x + shift[2] + off[0]) + 'px, ' + Math.round(y + shift[3] + off[1]) + 'px) translate(' + shift[0] + '%, ' + shift[1] + '%)';
33130
+ this._tooltipFor = { id: id, f: f };
33131
+ };
33132
+
33133
+ SMap.prototype._hideTooltip = function () {
33134
+ if (this._tooltip && this._tooltip.parentNode) { this._tooltip.parentNode.removeChild(this._tooltip); }
33135
+ this._tooltipFor = null;
33136
+ };
33137
+
33138
+ // Tooltips of a drawn layer: points show theirs beside the point, lines and areas at the pointer.
33139
+ SMap.prototype._tooltips = function (id, def, main) {
33140
+ var self = this, m = this.engine;
33141
+ this._listen(id, 'mousemove', main, function (e) {
33142
+ var f = e.features && e.features[0];
33143
+ if (!f || def.hidden) { return; }
33144
+ if (def.kind === 'points' && pointOf(f) && !(f.properties && f.properties.point_count)) {
33145
+ var mk = def.o.marker, k = mk ? scaleAt(mk.scale, m.getZoom()) : 1;
33146
+ var size = mk ? (mk.size || 32) * k : (def.o.radius || 6) * 2;
33147
+ var gap = mk && (mk.shape === undefined || mk.shape === 'pin') ? Math.round(size * 1.25) : Math.round(size / 2 + 4);
33148
+ self._showTooltip(id, def, f, { lngLat: pointOf(f), gap: gap });
33149
+ } else {
33150
+ self._showTooltip(id, def, f, { point: e.point, gap: 12 });
33151
+ }
33152
+ });
33153
+ this._listen(id, 'mouseleave', main, function () { if (self._tooltipFor && self._tooltipFor.id === id) { self._hideTooltip(); } });
33154
+ };
33155
+
33156
+ // ---- clusters drawn as HTML (G6)
33157
+
33158
+ // Colours of a ring: each value's share of the points, largest first; up to six slices, the rest in the last.
33159
+ function ringBackground(counts, fallback) {
33160
+ var keys = Object.keys(counts).sort(function (a, b) { return counts[b] - counts[a]; });
33161
+ var total = keys.reduce(function (t, k) { return t + counts[k]; }, 0);
33162
+ if (!total) { return fallback; }
33163
+ if (keys.length === 1) { return keys[0]; }
33164
+ var shown = keys.slice(0, 6), at = 0;
33165
+ return 'conic-gradient(' + shown.map(function (c, i) {
33166
+ var from = at;
33167
+ at = i === shown.length - 1 ? 100 : Math.min(100, at + Math.round(counts[c] / total * 100));
33168
+ return c + ' ' + from + '% ' + at + '%';
33169
+ }).join(', ') + ')';
33170
+ }
33171
+
33172
+ // The cluster as the caller's html() sees it.
33173
+ SMap.prototype._clusterInfo = function (src, f) {
33174
+ var m = this.engine, p = f.properties || {};
33175
+ return {
33176
+ id: p.cluster_id, count: p.point_count, properties: p, lngLat: pointOf(f),
33177
+ leaves: function (limit) {
33178
+ var source = m.getSource(src);
33179
+ return Promise.resolve(source.getClusterLeaves(p.cluster_id, limit === undefined ? Infinity : limit, 0));
33180
+ },
33181
+ };
33182
+ };
33183
+
33184
+ // HTML clusters of a point layer: the clusters the engine made are read after each change of view or data and laid
33185
+ // out as custom markers (kept by cluster id, so an unchanged cluster keeps its element).
33186
+ SMap.prototype._htmlClusters = function (id, def, src) {
33187
+ var self = this, m = this.engine, co = def.o.cluster;
33188
+ var ring = co.ring ? (typeof co.ring === 'string' ? { property: co.ring } : co.ring) : null;
33189
+ var render = function (props, f) {
33190
+ var info = self._clusterInfo(src, f);
33191
+ if (co.html) { return co.html(info); }
33192
+ var size = info.count >= 100 ? 44 : (info.count >= 10 ? 38 : 32);
33193
+ var doc = self._markerOverlay().ownerDocument;
33194
+ var el = doc.createElement('div');
33195
+ el.className = 'smap-cluster';
33196
+ el.style.width = el.style.height = size + 'px';
33197
+ el.style.background = ring.color || def.o.clusterColor || def.o.color || '#4f46e5';
33198
+ var b = doc.createElement('b');
33199
+ b.textContent = String(info.count);
33200
+ el.appendChild(b);
33201
+ // The ring: the share of each value among the cluster's points (read from at most ring.limit of them).
33202
+ info.leaves(ring.limit || 500).then(function (leaves) {
33203
+ var counts = {};
33204
+ (leaves || []).forEach(function (leaf) {
33205
+ var c = leaf.properties ? leaf.properties[ring.property] : undefined;
33206
+ if (typeof c === 'string' && c) { counts[c] = (counts[c] || 0) + 1; }
33207
+ });
33208
+ el.style.background = ringBackground(counts, el.style.background);
33209
+ }, function () {});
33210
+ return el;
33211
+ };
33212
+ def.clusterSet = {
33213
+ o: {
33214
+ render: render, anchor: 'center', className: co.className, riseOnHover: true,
33215
+ // A click zooms in to where the cluster splits (cluster.zoomOnClick: false turns it off).
33216
+ onClick: co.zoomOnClick === false ? co.onClick : function (f, e) {
33217
+ if (co.onClick) { co.onClick(f, e); }
33218
+ var source = m.getSource(src);
33219
+ Promise.resolve(source.getClusterExpansionZoom(f.properties.cluster_id)).then(function (zoom) {
33220
+ m.easeTo({ center: pointOf(f), zoom: zoom });
33221
+ }, function () {});
33222
+ },
33223
+ tooltip: co.tooltip ? function (p, f) { return co.tooltip(self._clusterInfo(src, f)); } : undefined,
33224
+ },
33225
+ data: { type: 'FeatureCollection', features: [] },
33226
+ custom: null,
33227
+ };
33228
+ var refresh = function () {
33229
+ var set = def.clusterSet;
33230
+ if (!set || !m.getSource(src)) { return; }
33231
+ var seen = {}, features = [];
33232
+ (m.querySourceFeatures(src, { filter: ['has', 'point_count'] }) || []).forEach(function (f) {
33233
+ var cid = f.properties && f.properties.cluster_id;
33234
+ if (cid === undefined || seen[cid]) { return; }
33235
+ seen[cid] = true;
33236
+ features.push({ type: 'Feature', id: 'c' + cid, properties: f.properties, geometry: { type: 'Point', coordinates: pointOf(f) } });
33237
+ });
33238
+ set.data = { type: 'FeatureCollection', features: features };
33239
+ self._markerOverlay();
33240
+ self._customData(id + ':clusters', set);
33241
+ };
33242
+ this._listen(id, 'moveend', null, refresh);
33243
+ this._listen(id, 'sourcedata', null, function (e) { if (e && e.sourceId === src && e.isSourceLoaded) { refresh(); } });
33244
+ refresh();
33245
+ };
33246
+
31111
33247
  // ------------------------------------------------------------------ map tools (M49-M57)
31112
33248
 
31113
33249
  var TOOL_ID = /^[A-Za-z0-9._-]{1,64}$/;
@@ -31122,6 +33258,8 @@ function smapCreateSdk(engine, interop, plan) {
31122
33258
  zoom: { control: 'NavigationControl', label: 'Zoom', position: 'top-left', options: { showCompass: false } },
31123
33259
  compass: { control: 'NavigationControl', label: 'Compass', position: 'top-left', options: { showZoom: false } },
31124
33260
  locate: { control: 'GeolocateControl', label: 'Locate', position: 'top-left' },
33261
+ // Made by the SDK itself: the base map and overlay switcher (G8).
33262
+ layers: { sdk: 'layers', label: 'Layers', position: 'top-right' },
31125
33263
  };
31126
33264
  var TOOLS_ICON = '<svg viewBox="0 0 24 24" width="18" height="18" aria-hidden="true" focusable="false" fill="none" ' +
31127
33265
  'stroke="currentColor" stroke-width="2" stroke-linecap="round"><path d="M4 7h10M18 7h2M4 17h2M10 17h10"/>' +
@@ -31192,7 +33330,7 @@ function smapCreateSdk(engine, interop, plan) {
31192
33330
  }
31193
33331
  if (typeof target === 'string') {
31194
33332
  if (!kind) { throw new Error('sMap: unknown tool kind "' + target + '"'); }
31195
- if (!engine[kind.control]) { throw new Error('sMap: the rendering engine has no ' + kind.control); }
33333
+ if (!kind.sdk && !this._lib[kind.control]) { throw new Error('sMap: the rendering engine has no ' + kind.control); }
31196
33334
  } else if (!isElement(target) && !(target && typeof target.onAdd === 'function')) {
31197
33335
  throw new Error('sMap: a tool is an element, an engine control or a tool kind');
31198
33336
  }
@@ -31201,7 +33339,8 @@ function smapCreateSdk(engine, interop, plan) {
31201
33339
  if (position === 'none' && !isElement(target)) { throw new Error('sMap: only an element may stay out of the map\'s corners'); }
31202
33340
  if (this._toolIndex(id) >= 0) { this.removeTool(id); }
31203
33341
  var tool = { id: id, label: String(o.label || (kind ? kind.label : id)), position: position, el: null, control: null };
31204
- if (kind) { tool.control = toolControl(tool, new engine[kind.control](o.options || kind.options)); }
33342
+ if (kind && kind.sdk === 'layers') { tool.control = toolControl(tool, layersControl(this, o.options || {})); }
33343
+ else if (kind) { tool.control = toolControl(tool, new this._lib[kind.control](o.options || kind.options)); }
31205
33344
  else if (!isElement(target)) { tool.control = toolControl(tool, target); }
31206
33345
  else if (position !== 'none') { tool.control = elementControl(tool, target); }
31207
33346
  else { tool.el = target; }
@@ -31454,6 +33593,1119 @@ function smapCreateSdk(engine, interop, plan) {
31454
33593
  return control;
31455
33594
  }
31456
33595
 
33596
+ // ------------------------------------------------------------------ heat maps (G7), terrain (G11), synced maps (G13), drawn tiles (G14)
33597
+
33598
+ /**
33599
+ * A heat map of points: weight (a number, or per feature: { property } or an expression; default 1), radius
33600
+ * (pixels, default 20, or an expression of the zoom), intensity (default 1), opacity (default 0.8), colors (from low
33601
+ * to high, or [[density 0–1, colour], …]), minzoom, maxzoom, slot, before, zIndex.
33602
+ */
33603
+ SMap.prototype.addHeatmap = function (id, data, o) {
33604
+ this._define(id, { kind: 'heatmap', data: toFeatureCollection(data), o: o || {} });
33605
+ return this;
33606
+ };
33607
+
33608
+ var TERRAIN_SOURCE = 'smap-terrain';
33609
+ var HILLSHADE_LAYER = 'smap-hillshade';
33610
+
33611
+ /**
33612
+ * Relief: the map drawn over elevation tiles (seen when the map is tilted), with optional hillshading.
33613
+ * @param {Object|null} terrain { tiles: [url with {z}/{x}/{y}], encoding: 'terrarium' | 'mapbox' (default terrarium),
33614
+ * tileSize (256), maxzoom (15), attribution, exaggeration (1), hillshade (true, or { exaggeration, shadow,
33615
+ * highlight }) }; null takes it off
33616
+ */
33617
+ SMap.prototype.setTerrain = function (terrain) {
33618
+ if (terrain && (!Array.isArray(terrain.tiles) || !terrain.tiles.length)) { throw new Error('sMap: terrain needs tiles'); }
33619
+ this._terrain = terrain ? Object.assign({}, terrain) : null;
33620
+ if (this.engine && this._styleReady) { this._applyTerrain(); }
33621
+ return this;
33622
+ };
33623
+
33624
+ SMap.prototype._applyTerrain = function () {
33625
+ var m = this.engine, t = this._terrain;
33626
+ if (m.setTerrain) { m.setTerrain(null); }
33627
+ if (m.getLayer(HILLSHADE_LAYER)) { m.removeLayer(HILLSHADE_LAYER); }
33628
+ if (m.getSource(TERRAIN_SOURCE)) { m.removeSource(TERRAIN_SOURCE); }
33629
+ if (m.getSource(TERRAIN_SOURCE + '-shade')) { m.removeSource(TERRAIN_SOURCE + '-shade'); }
33630
+ if (!t) { return; }
33631
+ var source = { type: 'raster-dem', tiles: t.tiles.slice(), tileSize: t.tileSize || 256, encoding: t.encoding || 'terrarium', maxzoom: t.maxzoom || 15 };
33632
+ if (t.attribution) { source.attribution = t.attribution; }
33633
+ m.addSource(TERRAIN_SOURCE, source);
33634
+ if (t.hillshade !== false) {
33635
+ var hs = t.hillshade && typeof t.hillshade === 'object' ? t.hillshade : {};
33636
+ var paint = { 'hillshade-exaggeration': hs.exaggeration !== undefined ? hs.exaggeration : 0.35 };
33637
+ if (hs.shadow) { paint['hillshade-shadow-color'] = hs.shadow; }
33638
+ if (hs.highlight) { paint['hillshade-highlight-color'] = hs.highlight; }
33639
+ // Over land and water, under the roads; from a source of its own (the engine draws the relief and the shading
33640
+ // better from two sources than from one).
33641
+ m.addSource(TERRAIN_SOURCE + '-shade', Object.assign({}, source, { tiles: source.tiles.slice() }));
33642
+ m.addLayer({ id: HILLSHADE_LAYER, type: 'hillshade', source: TERRAIN_SOURCE + '-shade', paint: paint }, this.slots().roads || undefined);
33643
+ }
33644
+ if (m.setTerrain) { m.setTerrain({ source: TERRAIN_SOURCE, exaggeration: t.exaggeration || 1 }); }
33645
+ };
33646
+
33647
+ /**
33648
+ * Keeps another sMap map on this map's view, both ways (a picture in picture, a before / after pair). `offsetZoom`
33649
+ * is added to this map's zoom on the other (e.g. -3 for an overview). Returns a function that ends it.
33650
+ */
33651
+ SMap.prototype.syncWith = function (other, options) {
33652
+ var self = this, offset = (options && options.offsetZoom) || 0, busy = false;
33653
+ if (!other || !(other instanceof SMap)) { throw new Error('sMap: syncWith takes another sMap map'); }
33654
+ var copy = function (from, to, dz) {
33655
+ return function () {
33656
+ if (busy || !from.engine || !to.engine) { return; }
33657
+ busy = true;
33658
+ try {
33659
+ var c = from.engine.getCenter();
33660
+ to.engine.jumpTo({ center: [c.lng, c.lat], zoom: from.engine.getZoom() + dz, bearing: from.engine.getBearing(), pitch: from.engine.getPitch() });
33661
+ } finally { busy = false; }
33662
+ };
33663
+ };
33664
+ var a = copy(this, other, offset), b = copy(other, this, -offset);
33665
+ Promise.all([this.ready, other.ready]).then(function () {
33666
+ if (!a) { return; }
33667
+ self.engine.on('move', a);
33668
+ other.engine.on('move', b);
33669
+ a();
33670
+ });
33671
+ return function () {
33672
+ if (self.engine) { self.engine.off('move', a); }
33673
+ if (other.engine) { other.engine.off('move', b); }
33674
+ a = null;
33675
+ };
33676
+ };
33677
+
33678
+ // Tiles drawn by the page: one protocol for every map, each layer its own key.
33679
+ var canvasTiles = {};
33680
+ var canvasSeq = 0;
33681
+ var canvasRegistered = false;
33682
+ function registerCanvasProtocol(doc) {
33683
+ if (canvasRegistered) { return; }
33684
+ canvasRegistered = true;
33685
+ var handler = function (params) {
33686
+ var m = /^smapcanvas:\/\/([^/]+)\/(\d+)\/(\d+)\/(\d+)/.exec(params.url);
33687
+ var entry = m && canvasTiles[m[1]];
33688
+ if (!entry) { return Promise.reject(new Error('sMap: no drawn tiles for ' + params.url)); }
33689
+ var size = entry.tileSize * entry.ratio;
33690
+ var canvas = entry.doc.createElement('canvas');
33691
+ canvas.width = size; canvas.height = size;
33692
+ var ctx = canvas.getContext('2d');
33693
+ ctx.scale(entry.ratio, entry.ratio);
33694
+ return Promise.resolve(entry.draw(ctx, +m[2], +m[3], +m[4], { size: entry.tileSize, canvas: canvas })).then(function () {
33695
+ return new Promise(function (resolve, reject) {
33696
+ canvas.toBlob(function (blob) {
33697
+ if (!blob) { reject(new Error('sMap: a drawn tile could not be encoded')); return; }
33698
+ blob.arrayBuffer().then(function (data) { resolve({ data: data }); }, reject);
33699
+ }, 'image/png');
33700
+ });
33701
+ });
33702
+ };
33703
+ if (engine && engine.addProtocol) { engine.addProtocol('smapcanvas', handler); }
33704
+ if (canvasLib) { canvasLib.addProtocol('smapcanvas', handler); }
33705
+ }
33706
+
33707
+ /**
33708
+ * Raster tiles drawn by the page: draw(ctx, z, x, y, { size, canvas }) paints one tile (a 2D context already scaled
33709
+ * to `size` × `size` CSS pixels; may return a promise). Options as addRasterLayer (tileSize 256, minzoom, maxzoom,
33710
+ * opacity, attribution, slot, before, zIndex).
33711
+ */
33712
+ SMap.prototype.addCanvasTiles = function (id, draw, o) {
33713
+ if (typeof draw !== 'function') { throw new Error('sMap: addCanvasTiles needs draw(ctx, z, x, y)'); }
33714
+ o = o || {};
33715
+ var doc = (this.engine && this.engine.getContainer().ownerDocument) || (typeof document !== 'undefined' ? document : null);
33716
+ if (!doc) { throw new Error('sMap: addCanvasTiles needs a page'); }
33717
+ registerCanvasProtocol(doc);
33718
+ var key = 'c' + (++canvasSeq);
33719
+ var win = doc.defaultView || {};
33720
+ canvasTiles[key] = { draw: draw, tileSize: o.tileSize || 256, ratio: Math.min(2, Math.max(1, Math.ceil(win.devicePixelRatio || 1))), doc: doc };
33721
+ var source = { type: 'raster', tiles: ['smapcanvas://' + key + '/{z}/{x}/{y}'], tileSize: o.tileSize || 256 };
33722
+ copyKeys(o, source, ['attribution', 'minzoom', 'maxzoom', 'bounds']);
33723
+ return this._addRaster(id, source, o);
33724
+ };
33725
+
33726
+ // ------------------------------------------------------------------ drawing and editing shapes (G3), area selection (G4)
33727
+
33728
+ var DRAW_TEXT = {
33729
+ polygon: 'Polygon', rectangle: 'Rectangle', circle: 'Circle', line: 'Line', point: 'Point', hole: 'Hole',
33730
+ delete: 'Delete', undo: 'Undo', redo: 'Redo', finish: 'Finish', cancel: 'Cancel',
33731
+ };
33732
+ var DRAW_MODES = ['polygon', 'rectangle', 'circle', 'line', 'point'];
33733
+ var SNAP_PX = 10;
33734
+ var drawSeq = 0;
33735
+
33736
+ function closeRing(ring) {
33737
+ var r = ring.slice();
33738
+ if (r.length && (r[0][0] !== r[r.length - 1][0] || r[0][1] !== r[r.length - 1][1])) { r.push(r[0].slice()); }
33739
+ return r;
33740
+ }
33741
+ function openRing(ring) { return ring.length > 1 && ring[0][0] === ring[ring.length - 1][0] && ring[0][1] === ring[ring.length - 1][1] ? ring.slice(0, -1) : ring.slice(); }
33742
+
33743
+ // A circle of `radius` metres as a ring of 64 points.
33744
+ function circleRing(center, radius) {
33745
+ // The same Earth radius as sMap.geo.distance, so the radius handle measures what was drawn.
33746
+ var ring = [], R = 6371008.8, lat = center[1] * Math.PI / 180;
33747
+ for (var i = 0; i <= 64; i++) {
33748
+ var a = (i % 64) / 64 * 2 * Math.PI;
33749
+ ring.push([center[0] + (radius * Math.sin(a)) / (R * Math.cos(lat)) * 180 / Math.PI, center[1] + (radius * Math.cos(a)) / R * 180 / Math.PI]);
33750
+ }
33751
+ return ring;
33752
+ }
33753
+
33754
+ // The editable rings of a geometry: [{ path: [polygon, ring] or [ring], coords (open), closed }].
33755
+ function ringsOf(g) {
33756
+ if (!g) { return []; }
33757
+ if (g.type === 'LineString') { return [{ path: [], coords: g.coordinates, closed: false }]; }
33758
+ if (g.type === 'Polygon') { return g.coordinates.map(function (r, i) { return { path: [i], coords: openRing(r), closed: true }; }); }
33759
+ if (g.type === 'MultiPolygon') {
33760
+ var out = [];
33761
+ g.coordinates.forEach(function (poly, p) { poly.forEach(function (r, i) { out.push({ path: [p, i], coords: openRing(r), closed: true }); }); });
33762
+ return out;
33763
+ }
33764
+ return [];
33765
+ }
33766
+
33767
+ function setRing(g, path, coords) {
33768
+ if (g.type === 'LineString') { g.coordinates = coords; return; }
33769
+ if (g.type === 'Polygon') { g.coordinates[path[0]] = closeRing(coords); return; }
33770
+ if (g.type === 'MultiPolygon') { g.coordinates[path[0]][path[1]] = closeRing(coords); }
33771
+ }
33772
+
33773
+ function moveGeometry(g, dx, dy) {
33774
+ (function walk(c) { if (typeof c[0] === 'number') { c[0] += dx; c[1] += dy; } else { c.forEach(walk); } })(g.coordinates);
33775
+ }
33776
+
33777
+ /**
33778
+ * A drawing and editing tool on this map. Shapes are kept by the tool as GeoJSON features (each with an id) and drawn
33779
+ * in its own layers; your page reads them with getAll() or from the events.
33780
+ * @param {Object} [o]
33781
+ * features (GeoJSON to start from), modes (the shapes offered, default all: polygon, rectangle, circle, line, point),
33782
+ * snap (true: a new or moved vertex within 10 px of another shape's vertex takes its place; default true),
33783
+ * toolbar (false, or a corner; default 'top-left'), labels (the toolbar's texts), color (default '#2563eb'),
33784
+ * onChange({ type: 'created' | 'edited' | 'deleted', feature, features }) after every change
33785
+ */
33786
+ SMap.prototype.drawTool = function (o) {
33787
+ return new DrawTool(this, o || {});
33788
+ };
33789
+
33790
+ function DrawTool(map, o) {
33791
+ this.map = map;
33792
+ this.o = o;
33793
+ this.id = 'smap-draw-' + (++drawSeq);
33794
+ this.color = o.color || '#2563eb';
33795
+ this.modes = (o.modes || DRAW_MODES).filter(function (k) { return DRAW_MODES.indexOf(k) >= 0; });
33796
+ this.snap = o.snap !== false;
33797
+ this.text = Object.assign({}, DRAW_TEXT, o.labels || {});
33798
+ this.features = [];
33799
+ this.seq = 0;
33800
+ this.selected = null; // feature id
33801
+ this.vertex = null; // { ring, index } of the selected vertex
33802
+ this.mode = null; // the shape being drawn
33803
+ this.sketch = null; // coordinates of the shape being drawn
33804
+ this.hover = null;
33805
+ this.undoStack = [];
33806
+ this.redoStack = [];
33807
+ this.handlers = {};
33808
+ var self = this;
33809
+ (o.features ? toFeatureCollection(o.features).features : []).forEach(function (f) { self.features.push(self._own(f)); });
33810
+ map.ready.then(function () { if (!self.destroyed) { self._mount(); } });
33811
+ }
33812
+
33813
+ DrawTool.prototype._own = function (f) {
33814
+ var copy = JSON.parse(JSON.stringify(f));
33815
+ if (copy.id === undefined || copy.id === null) { copy.id = 'f' + (++this.seq); }
33816
+ copy.properties = copy.properties || {};
33817
+ return copy;
33818
+ };
33819
+
33820
+ DrawTool.prototype.on = function (type, fn) { (this.handlers[type] = this.handlers[type] || []).push(fn); return this; };
33821
+ DrawTool.prototype.off = function (type, fn) { this.handlers[type] = (this.handlers[type] || []).filter(function (h) { return h !== fn; }); return this; };
33822
+ DrawTool.prototype._emit = function (type, feature) {
33823
+ var e = { type: type, feature: feature ? JSON.parse(JSON.stringify(feature)) : null, features: this.getAll() };
33824
+ (this.handlers[type] || []).slice().forEach(function (h) { h(e); });
33825
+ (this.handlers.change || []).slice().forEach(function (h) { h(e); });
33826
+ if (this.o.onChange) { this.o.onChange(e); }
33827
+ };
33828
+
33829
+ /** Every shape as a FeatureCollection (a copy). */
33830
+ DrawTool.prototype.getAll = function () { return JSON.parse(JSON.stringify({ type: 'FeatureCollection', features: this.features })); };
33831
+ DrawTool.prototype.get = function (id) { var f = this._find(id); return f ? JSON.parse(JSON.stringify(f)) : null; };
33832
+ /** Replaces every shape (not recorded for undo). */
33833
+ DrawTool.prototype.set = function (data) {
33834
+ var self = this;
33835
+ this.features = toFeatureCollection(data).features.map(function (f) { return self._own(f); });
33836
+ this.selected = null; this.vertex = null;
33837
+ this.undoStack = []; this.redoStack = [];
33838
+ this._render();
33839
+ return this;
33840
+ };
33841
+ DrawTool.prototype._find = function (id) { for (var i = 0; i < this.features.length; i++) { if (this.features[i].id === id) { return this.features[i]; } } return null; };
33842
+ DrawTool.prototype._record = function () {
33843
+ this.undoStack.push(JSON.stringify(this.features));
33844
+ if (this.undoStack.length > 100) { this.undoStack.shift(); }
33845
+ this.redoStack = [];
33846
+ };
33847
+ DrawTool.prototype.undo = function () {
33848
+ if (!this.undoStack.length) { return this; }
33849
+ this.redoStack.push(JSON.stringify(this.features));
33850
+ this.features = JSON.parse(this.undoStack.pop());
33851
+ if (this.selected && !this._find(this.selected)) { this.selected = null; }
33852
+ this.vertex = null;
33853
+ this._render();
33854
+ this._emit('edited', this.selected ? this._find(this.selected) : null);
33855
+ return this;
33856
+ };
33857
+ DrawTool.prototype.redo = function () {
33858
+ if (!this.redoStack.length) { return this; }
33859
+ this.undoStack.push(JSON.stringify(this.features));
33860
+ this.features = JSON.parse(this.redoStack.pop());
33861
+ if (this.selected && !this._find(this.selected)) { this.selected = null; }
33862
+ this.vertex = null;
33863
+ this._render();
33864
+ this._emit('edited', this.selected ? this._find(this.selected) : null);
33865
+ return this;
33866
+ };
33867
+
33868
+ /** Starts drawing a shape: 'polygon', 'rectangle', 'circle', 'line', 'point', or 'hole' (in the selected polygon). */
33869
+ DrawTool.prototype.start = function (mode) {
33870
+ if (mode === 'hole') {
33871
+ var f = this.selected && this._find(this.selected);
33872
+ if (!f || !f.geometry || f.geometry.type !== 'Polygon') { throw new Error('sMap: select a polygon to draw a hole in'); }
33873
+ } else if (DRAW_MODES.indexOf(mode) < 0) { throw new Error('sMap: unknown shape "' + mode + '"'); }
33874
+ this.mode = mode;
33875
+ this.sketch = [];
33876
+ this.vertex = null;
33877
+ if (mode !== 'hole') { this.selected = null; }
33878
+ this._render();
33879
+ this._renderToolbar();
33880
+ return this;
33881
+ };
33882
+
33883
+ /** Stops drawing without keeping the shape being drawn. */
33884
+ DrawTool.prototype.cancel = function () { this.mode = null; this.sketch = null; this._render(); this._renderToolbar(); return this; };
33885
+
33886
+ /** Selects a shape for editing (null to deselect). */
33887
+ DrawTool.prototype.select = function (id) { this.selected = id && this._find(id) ? id : null; this.vertex = null; this._render(); this._renderToolbar(); return this; };
33888
+ DrawTool.prototype.selection = function () { return this.selected; };
33889
+
33890
+ /** Deletes a shape (default: the selected one); with a vertex selected, deletes that vertex instead. */
33891
+ DrawTool.prototype.delete = function (id) {
33892
+ if (id === undefined && this.vertex && this.selected) { return this._deleteVertex(); }
33893
+ id = id === undefined ? this.selected : id;
33894
+ var f = this._find(id);
33895
+ if (!f) { return this; }
33896
+ this._record();
33897
+ this.features = this.features.filter(function (x) { return x !== f; });
33898
+ if (this.selected === id) { this.selected = null; this.vertex = null; }
33899
+ this._render();
33900
+ this._renderToolbar();
33901
+ this._emit('deleted', f);
33902
+ return this;
33903
+ };
33904
+
33905
+ DrawTool.prototype._deleteVertex = function () {
33906
+ var f = this._find(this.selected), v = this.vertex;
33907
+ var rings = ringsOf(f.geometry), r = rings[v.ring];
33908
+ if (!r || r.coords.length <= (r.closed ? 3 : 2)) { return this; }
33909
+ this._record();
33910
+ var coords = r.coords.slice();
33911
+ coords.splice(v.index, 1);
33912
+ setRing(f.geometry, r.path, coords);
33913
+ this.vertex = null;
33914
+ this._render();
33915
+ this._emit('edited', f);
33916
+ return this;
33917
+ };
33918
+
33919
+ DrawTool.prototype.destroy = function () {
33920
+ this.destroyed = true;
33921
+ var m = this.map.engine;
33922
+ if (!m) { return; }
33923
+ var self = this;
33924
+ (this.listeners || []).forEach(function (l) { if (l[1]) { m.off(l[0], l[1], l[2]); } else { m.off(l[0], l[2]); } });
33925
+ [this.id + '-fill', this.id + '-line', this.id + '-sketch', this.id + '-vertex', this.id + '-mid'].forEach(function (l) { if (m.getLayer(l)) { m.removeLayer(l); } });
33926
+ if (m.getSource(this.id)) { m.removeSource(this.id); }
33927
+ if (this.toolbar) { m.removeControl(this.toolbar); }
33928
+ if (this.keyListener) { m.getContainer().removeEventListener('keydown', this.keyListener); }
33929
+ if (this.panOff && m.dragPan) { m.dragPan.enable(); }
33930
+ if (m.doubleClickZoom && this.dblWasOn) { m.doubleClickZoom.enable(); }
33931
+ self.map._drawTools = (self.map._drawTools || []).filter(function (t) { return t !== self; });
33932
+ };
33933
+
33934
+ DrawTool.prototype._listen = function (type, layer, fn) {
33935
+ var m = this.map.engine;
33936
+ if (layer) { m.on(type, layer, fn); } else { m.on(type, fn); }
33937
+ (this.listeners = this.listeners || []).push([type, layer, fn]);
33938
+ };
33939
+
33940
+ DrawTool.prototype._mount = function () {
33941
+ var self = this, m = this.map.engine;
33942
+ this.map._drawTools = (this.map._drawTools || []).concat([this]);
33943
+ this._addLayers();
33944
+ // The map's style changes drop every layer: the tool's come back with the map's own.
33945
+ this._listen('style.load', null, function () { self._addLayers(); });
33946
+ this._listen('mousedown', null, function (e) { self._down(e); });
33947
+ this._listen('touchstart', null, function (e) { if (e.points && e.points.length === 1) { self._down(e); } });
33948
+ this._listen('mousemove', null, function (e) { self._move(e); });
33949
+ this._listen('touchmove', null, function (e) { self._move(e); });
33950
+ this._listen('mouseup', null, function (e) { self._up(e); });
33951
+ this._listen('touchend', null, function (e) { self._up(e); });
33952
+ this._listen('click', null, function (e) { self._click(e); });
33953
+ this._listen('dblclick', null, function (e) { if (self.mode === 'polygon' || self.mode === 'line' || self.mode === 'hole') { e.preventDefault(); self._finish(); } });
33954
+ if (m.doubleClickZoom && m.doubleClickZoom.isEnabled && m.doubleClickZoom.isEnabled()) { this.dblWasOn = true; }
33955
+ var el = m.getContainer();
33956
+ this.keyListener = function (ev) {
33957
+ if (ev.key === 'Escape') { if (self.mode) { self.cancel(); } else { self.select(null); } }
33958
+ else if (ev.key === 'Enter' && self.mode) { self._finish(); }
33959
+ else if ((ev.key === 'Backspace' || ev.key === 'Delete') && self.mode && self.sketch && self.sketch.length) { self.sketch.pop(); self._render(); ev.preventDefault(); }
33960
+ else if ((ev.key === 'Backspace' || ev.key === 'Delete') && self.selected) { self.delete(); ev.preventDefault(); }
33961
+ else if ((ev.ctrlKey || ev.metaKey) && ev.key.toLowerCase() === 'z') { if (ev.shiftKey) { self.redo(); } else { self.undo(); } ev.preventDefault(); }
33962
+ };
33963
+ el.addEventListener('keydown', this.keyListener);
33964
+ if (this.o.toolbar !== false) {
33965
+ this.toolbar = this._toolbarControl();
33966
+ m.addControl(this.toolbar, typeof this.o.toolbar === 'string' ? this.o.toolbar : 'top-left');
33967
+ }
33968
+ this._render();
33969
+ };
33970
+
33971
+ DrawTool.prototype._addLayers = function () {
33972
+ var m = this.map.engine, id = this.id, c = this.color;
33973
+ if (m.getSource(id)) { return; }
33974
+ m.addSource(id, { type: 'geojson', data: { type: 'FeatureCollection', features: [] } });
33975
+ var role = function (r) { return ['==', ['get', '_role'], r]; };
33976
+ m.addLayer({ id: id + '-fill', type: 'fill', source: id, filter: ['all', ['==', ['geometry-type'], 'Polygon'], ['!', role('sketch')]],
33977
+ paint: { 'fill-color': ['coalesce', ['get', '_fill'], c], 'fill-opacity': ['case', ['==', ['get', '_selected'], true], 0.3, 0.18] } });
33978
+ m.addLayer({ id: id + '-line', type: 'line', source: id, filter: ['all', ['!=', ['geometry-type'], 'Point'], ['!', role('sketch')]],
33979
+ layout: { 'line-join': 'round', 'line-cap': 'round' },
33980
+ paint: { 'line-color': ['coalesce', ['get', '_stroke'], c], 'line-width': ['case', ['==', ['get', '_selected'], true], 3, 2] } });
33981
+ m.addLayer({ id: id + '-sketch', type: 'line', source: id, filter: role('sketch'),
33982
+ layout: { 'line-join': 'round', 'line-cap': 'round' }, paint: { 'line-color': c, 'line-width': 2, 'line-dasharray': [2, 1.5] } });
33983
+ m.addLayer({ id: id + '-mid', type: 'circle', source: id, filter: role('mid'),
33984
+ paint: { 'circle-radius': 4, 'circle-color': '#ffffff', 'circle-opacity': 0.9, 'circle-stroke-width': 1.5, 'circle-stroke-color': c } });
33985
+ m.addLayer({ id: id + '-vertex', type: 'circle', source: id, filter: ['any', role('vertex'), role('point'), role('sketch-vertex')],
33986
+ paint: { 'circle-radius': ['case', ['==', ['get', '_active'], true], 7, ['==', ['get', '_role'], 'point'], 7, 5],
33987
+ 'circle-color': ['case', ['==', ['get', '_active'], true], c, '#ffffff'], 'circle-stroke-width': 2, 'circle-stroke-color': c } });
33988
+ };
33989
+
33990
+ // What is drawn: every shape, the selected one's vertices and midpoints, and the shape being drawn.
33991
+ DrawTool.prototype._render = function () {
33992
+ var m = this.map.engine;
33993
+ if (!m || this.destroyed) { return; }
33994
+ var out = [], self = this;
33995
+ this.features.forEach(function (f) {
33996
+ var sel = f.id === self.selected;
33997
+ var props = { _id: f.id, _selected: sel };
33998
+ if (f.properties && f.properties.fill) { props._fill = f.properties.fill; }
33999
+ if (f.properties && f.properties.stroke) { props._stroke = f.properties.stroke; }
34000
+ if (f.geometry.type === 'Point') { props._role = 'point'; props._active = sel; }
34001
+ out.push({ type: 'Feature', properties: props, geometry: f.geometry });
34002
+ if (!sel || f.geometry.type === 'Point') { return; }
34003
+ if (f.properties && f.properties.shape === 'circle' && f.properties.center) {
34004
+ // A circle: one handle on its edge (east) sets the radius.
34005
+ out.push({ type: 'Feature', properties: { _role: 'vertex', _id: f.id, _radius: true, _active: false }, geometry: { type: 'Point', coordinates: circleRing(f.properties.center, f.properties.radius)[16] } });
34006
+ return;
34007
+ }
34008
+ ringsOf(f.geometry).forEach(function (r, ri) {
34009
+ r.coords.forEach(function (c, i) {
34010
+ var active = !!self.vertex && self.vertex.ring === ri && self.vertex.index === i;
34011
+ out.push({ type: 'Feature', properties: { _role: 'vertex', _id: f.id, _ring: ri, _index: i, _active: active }, geometry: { type: 'Point', coordinates: c } });
34012
+ var next = r.coords[i + 1] || (r.closed ? r.coords[0] : null);
34013
+ if (next && !(f.properties && f.properties.shape === 'rectangle')) {
34014
+ out.push({ type: 'Feature', properties: { _role: 'mid', _id: f.id, _ring: ri, _index: i + 1 }, geometry: { type: 'Point', coordinates: [(c[0] + next[0]) / 2, (c[1] + next[1]) / 2] } });
34015
+ }
34016
+ });
34017
+ });
34018
+ });
34019
+ if (this.mode && this.sketch) {
34020
+ var pts = this.sketch.concat(this.hover ? [this.hover] : []);
34021
+ if (pts.length >= 2) {
34022
+ var closed = this.mode !== 'line' && pts.length >= 3;
34023
+ out.push({ type: 'Feature', properties: { _role: 'sketch' }, geometry: { type: 'LineString', coordinates: closed ? pts.concat([pts[0]]) : pts } });
34024
+ }
34025
+ this.sketch.forEach(function (c) { out.push({ type: 'Feature', properties: { _role: 'sketch-vertex' }, geometry: { type: 'Point', coordinates: c } }); });
34026
+ }
34027
+ var src = m.getSource(this.id);
34028
+ if (src) { src.setData({ type: 'FeatureCollection', features: out }); }
34029
+ };
34030
+
34031
+ DrawTool.prototype._lngLat = function (e) { return [e.lngLat.lng, e.lngLat.lat]; };
34032
+
34033
+ // A position taken over by a vertex of another shape within SNAP_PX pixels (when snapping is on).
34034
+ DrawTool.prototype._snapped = function (e, except) {
34035
+ if (!this.snap) { return this._lngLat(e); }
34036
+ var m = this.map.engine, best = null, bestD = SNAP_PX;
34037
+ this.features.forEach(function (f) {
34038
+ if (f.id === except) { return; }
34039
+ var pts = f.geometry.type === 'Point' ? [f.geometry.coordinates] : [];
34040
+ ringsOf(f.geometry).forEach(function (r) { pts = pts.concat(r.coords); });
34041
+ pts.forEach(function (c) {
34042
+ var p = m.project(c), d = Math.sqrt(Math.pow(p.x - e.point.x, 2) + Math.pow(p.y - e.point.y, 2));
34043
+ if (d <= bestD) { bestD = d; best = c; }
34044
+ });
34045
+ });
34046
+ return best ? best.slice() : this._lngLat(e);
34047
+ };
34048
+
34049
+ DrawTool.prototype._hit = function (e, layers) {
34050
+ var m = this.map.engine, self = this;
34051
+ var ids = layers.map(function (l) { return self.id + '-' + l; }).filter(function (l) { return m.getLayer(l); });
34052
+ if (!ids.length) { return null; }
34053
+ var r = 4, box = [[e.point.x - r, e.point.y - r], [e.point.x + r, e.point.y + r]];
34054
+ var hits = m.queryRenderedFeatures(box, { layers: ids }) || [];
34055
+ return hits[0] || null;
34056
+ };
34057
+
34058
+ DrawTool.prototype._pan = function (on) {
34059
+ var m = this.map.engine;
34060
+ if (!m.dragPan) { return; }
34061
+ if (on && this.panOff) { m.dragPan.enable(); this.panOff = false; }
34062
+ else if (!on && !this.panOff && (!m.dragPan.isEnabled || m.dragPan.isEnabled())) { m.dragPan.disable(); this.panOff = true; }
34063
+ };
34064
+
34065
+ DrawTool.prototype._down = function (e) {
34066
+ if (e.originalEvent && e.originalEvent.button !== undefined && e.originalEvent.button !== 0) { return; }
34067
+ var self = this;
34068
+ if (this.mode === 'rectangle' || this.mode === 'circle') {
34069
+ e.preventDefault();
34070
+ this._pan(false);
34071
+ this.drag = { kind: this.mode, start: this._snapped(e) };
34072
+ return;
34073
+ }
34074
+ if (this.mode) { return; }
34075
+ if (!this.selected) { return; }
34076
+ var f = this._find(this.selected);
34077
+ var hit = this._hit(e, ['vertex', 'mid']);
34078
+ if (hit && hit.properties._id === this.selected) {
34079
+ e.preventDefault();
34080
+ this._pan(false);
34081
+ var p = hit.properties;
34082
+ if (p._radius) {
34083
+ this._record();
34084
+ this.drag = { kind: 'radius', moved: false };
34085
+ return;
34086
+ }
34087
+ if (p._role === 'mid') {
34088
+ // A midpoint dragged becomes a new vertex.
34089
+ this._record();
34090
+ var rings = ringsOf(f.geometry), r = rings[p._ring], coords = r.coords.slice();
34091
+ coords.splice(p._index, 0, hit.geometry.coordinates.slice());
34092
+ setRing(f.geometry, r.path, coords);
34093
+ this.vertex = { ring: p._ring, index: p._index };
34094
+ } else {
34095
+ this._record();
34096
+ this.vertex = { ring: p._ring, index: p._index };
34097
+ }
34098
+ this.drag = { kind: 'vertex', moved: false };
34099
+ this._render();
34100
+ return;
34101
+ }
34102
+ var body = this._hit(e, ['fill', 'line', 'vertex']);
34103
+ if (body && body.properties._id === this.selected) {
34104
+ e.preventDefault();
34105
+ this._pan(false);
34106
+ this._record();
34107
+ this.drag = { kind: 'move', last: this._lngLat(e), moved: false };
34108
+ self.vertex = null;
34109
+ }
34110
+ };
34111
+
34112
+ DrawTool.prototype._move = function (e) {
34113
+ if (this.mode && this.sketch && !this.drag) { this.hover = this._snapped(e); this._render(); }
34114
+ var d = this.drag;
34115
+ if (!d) { return; }
34116
+ var f = this.selected && this._find(this.selected);
34117
+ if (d.kind === 'rectangle' || d.kind === 'circle') {
34118
+ d.end = this._lngLat(e);
34119
+ var shape = this._dragShape(d);
34120
+ this.sketch = shape ? openRing(shape) : [];
34121
+ this.hover = null;
34122
+ this._render();
34123
+ return;
34124
+ }
34125
+ if (!f) { return; }
34126
+ d.moved = true;
34127
+ if (d.kind === 'radius') {
34128
+ f.properties.radius = interop.geo.distance(f.properties.center, this._lngLat(e));
34129
+ f.geometry.coordinates = [circleRing(f.properties.center, f.properties.radius)];
34130
+ } else if (d.kind === 'vertex' && f.properties && f.properties.shape === 'rectangle') {
34131
+ // A rectangle stays a rectangle: the opposite corner stays, the dragged one follows the pointer.
34132
+ var cs = ringsOf(f.geometry)[0].coords, opp = cs[(this.vertex.index + 2) % 4], at = this._snapped(e, f.id);
34133
+ var rect = [[opp[0], opp[1]], [at[0], opp[1]], [at[0], at[1]], [opp[0], at[1]]];
34134
+ // Keep the dragged corner at its index.
34135
+ var shift = (this.vertex.index + 2) % 4, ordered = [];
34136
+ for (var q = 0; q < 4; q++) { ordered[(shift + q) % 4] = rect[q]; }
34137
+ f.geometry.coordinates = [closeRing(ordered)];
34138
+ } else if (d.kind === 'vertex') {
34139
+ var rings = ringsOf(f.geometry), r = rings[this.vertex.ring], coords = r.coords.slice();
34140
+ coords[this.vertex.index] = this._snapped(e, f.id);
34141
+ setRing(f.geometry, r.path, coords);
34142
+ } else if (d.kind === 'move') {
34143
+ var now = this._lngLat(e);
34144
+ if (f.properties && f.properties.shape === 'circle' && f.properties.center) {
34145
+ f.properties.center = [f.properties.center[0] + now[0] - d.last[0], f.properties.center[1] + now[1] - d.last[1]];
34146
+ }
34147
+ moveGeometry(f.geometry, now[0] - d.last[0], now[1] - d.last[1]);
34148
+ d.last = now;
34149
+ }
34150
+ this._render();
34151
+ };
34152
+
34153
+ DrawTool.prototype._dragShape = function (d) {
34154
+ if (!d.end) { return null; }
34155
+ if (d.kind === 'rectangle') {
34156
+ var a = d.start, b = d.end;
34157
+ return [[a[0], a[1]], [b[0], a[1]], [b[0], b[1]], [a[0], b[1]], [a[0], a[1]]];
34158
+ }
34159
+ var radius = interop.geo.distance(d.start, d.end);
34160
+ return radius > 0 ? circleRing(d.start, radius) : null;
34161
+ };
34162
+
34163
+ DrawTool.prototype._up = function (e) {
34164
+ var d = this.drag;
34165
+ if (!d) { return; }
34166
+ this.drag = null;
34167
+ this._pan(true);
34168
+ this._suppressClick = true;
34169
+ var self = this;
34170
+ setTimeout(function () { self._suppressClick = false; }, 0);
34171
+ if (d.kind === 'rectangle' || d.kind === 'circle') {
34172
+ d.end = this._lngLat(e);
34173
+ var ring = this._dragShape(d);
34174
+ var mode = this.mode;
34175
+ this.mode = null; this.sketch = null; this.hover = null;
34176
+ if (ring && Math.abs(ring[0][0] - ring[2][0]) + Math.abs(ring[0][1] - ring[2][1]) > 0) {
34177
+ var props = mode === 'circle' ? { shape: 'circle', center: d.start, radius: interop.geo.distance(d.start, d.end) } : { shape: 'rectangle' };
34178
+ this._add({ type: 'Feature', properties: props, geometry: { type: 'Polygon', coordinates: [ring] } });
34179
+ } else { this._render(); this._renderToolbar(); }
34180
+ return;
34181
+ }
34182
+ if (d.moved) { this._emit('edited', this._find(this.selected)); } else { this.undoStack.pop(); }
34183
+ this._render();
34184
+ };
34185
+
34186
+ DrawTool.prototype._click = function (e) {
34187
+ if (this._suppressClick) { return; }
34188
+ var self = this;
34189
+ if (this.mode === 'point') { this.mode = null; this.sketch = null; this._add({ type: 'Feature', properties: {}, geometry: { type: 'Point', coordinates: this._snapped(e) } }); return; }
34190
+ if (this.mode === 'polygon' || this.mode === 'line' || this.mode === 'hole') {
34191
+ var at = this._snapped(e);
34192
+ // A click on the first vertex closes a polygon.
34193
+ if (this.mode !== 'line' && this.sketch.length >= 3) {
34194
+ var first = this.map.engine.project(this.sketch[0]);
34195
+ if (Math.abs(first.x - e.point.x) <= SNAP_PX && Math.abs(first.y - e.point.y) <= SNAP_PX) { this._finish(); return; }
34196
+ }
34197
+ var last = this.sketch[this.sketch.length - 1];
34198
+ if (!last || last[0] !== at[0] || last[1] !== at[1]) { this.sketch.push(at); }
34199
+ this._render();
34200
+ return;
34201
+ }
34202
+ if (this.mode) { return; }
34203
+ // Not drawing: a click selects the shape under it (or a vertex of the selected one), elsewhere deselects.
34204
+ var v = this.selected && this._hit(e, ['vertex']);
34205
+ if (v && v.properties._id === this.selected && v.properties._role === 'vertex') {
34206
+ this.vertex = { ring: v.properties._ring, index: v.properties._index };
34207
+ this._render();
34208
+ return;
34209
+ }
34210
+ var hit = this._hit(e, ['vertex', 'line', 'fill']);
34211
+ self.select(hit ? hit.properties._id : null);
34212
+ };
34213
+
34214
+ DrawTool.prototype._finish = function () {
34215
+ var mode = this.mode, pts = (this.sketch || []).slice();
34216
+ this.mode = null; this.sketch = null; this.hover = null;
34217
+ if (mode === 'line' && pts.length >= 2) { this._add({ type: 'Feature', properties: {}, geometry: { type: 'LineString', coordinates: pts } }); return; }
34218
+ if (mode === 'polygon' && pts.length >= 3) { this._add({ type: 'Feature', properties: {}, geometry: { type: 'Polygon', coordinates: [closeRing(pts)] } }); return; }
34219
+ if (mode === 'hole' && pts.length >= 3) {
34220
+ var f = this._find(this.selected);
34221
+ if (f && f.geometry.type === 'Polygon') {
34222
+ this._record();
34223
+ f.geometry.coordinates.push(closeRing(pts));
34224
+ this._render(); this._renderToolbar();
34225
+ this._emit('edited', f);
34226
+ return;
34227
+ }
34228
+ }
34229
+ this._render();
34230
+ this._renderToolbar();
34231
+ };
34232
+
34233
+ DrawTool.prototype._add = function (feature) {
34234
+ this._record();
34235
+ var f = this._own(feature);
34236
+ this.features.push(f);
34237
+ this.selected = f.geometry.type === 'Point' ? null : f.id;
34238
+ this.vertex = null;
34239
+ this._render();
34240
+ this._renderToolbar();
34241
+ this._emit('created', f);
34242
+ };
34243
+
34244
+ DrawTool.prototype._toolbarControl = function () {
34245
+ var self = this;
34246
+ return {
34247
+ onAdd: function (m) {
34248
+ var doc = m.getContainer().ownerDocument;
34249
+ var el = doc.createElement('div');
34250
+ el.className = 'maplibregl-ctrl maplibregl-ctrl-group smap-draw';
34251
+ self.toolbarEl = el;
34252
+ self._renderToolbar();
34253
+ return el;
34254
+ },
34255
+ onRemove: function () { if (self.toolbarEl && self.toolbarEl.parentNode) { self.toolbarEl.parentNode.removeChild(self.toolbarEl); } self.toolbarEl = null; },
34256
+ };
34257
+ };
34258
+
34259
+ var DRAW_ICONS = {
34260
+ polygon: '<path d="M5 7l7-4 7 5-2 10H7z"/>', rectangle: '<rect x="4" y="6" width="16" height="12"/>',
34261
+ circle: '<circle cx="12" cy="12" r="8"/>', line: '<path d="M4 18 10 8l4 6 6-10"/>', point: '<circle cx="12" cy="12" r="3"/><path d="M12 3v3M12 18v3M3 12h3M18 12h3"/>',
34262
+ hole: '<path d="M5 7l7-4 7 5-2 10H7z"/><circle cx="12" cy="11" r="2.5"/>', delete: '<path d="M5 7h14M9 7V4h6v3M7 7l1 13h8l1-13"/>',
34263
+ undo: '<path d="M9 14 4 9l5-5"/><path d="M4 9h10a6 6 0 0 1 0 12h-3"/>', redo: '<path d="m15 14 5-5-5-5"/><path d="M20 9H10a6 6 0 0 0 0 12h3"/>',
34264
+ };
34265
+
34266
+ DrawTool.prototype._renderToolbar = function () {
34267
+ var el = this.toolbarEl;
34268
+ if (!el) { return; }
34269
+ var self = this, doc = el.ownerDocument;
34270
+ while (el.firstChild) { el.removeChild(el.firstChild); }
34271
+ var selectedPolygon = this.selected && this._find(this.selected) && this._find(this.selected).geometry.type === 'Polygon' && !(this._find(this.selected).properties.shape);
34272
+ var buttons = this.modes.slice();
34273
+ if (selectedPolygon) { buttons.push('hole'); }
34274
+ buttons = buttons.concat(['delete', 'undo', 'redo']);
34275
+ buttons.forEach(function (k) {
34276
+ var b = doc.createElement('button');
34277
+ b.type = 'button';
34278
+ b.className = 'smap-draw-' + k;
34279
+ b.title = self.text[k];
34280
+ b.setAttribute('aria-label', self.text[k]);
34281
+ b.innerHTML = '<svg viewBox="0 0 24 24" width="18" height="18" aria-hidden="true" focusable="false" fill="none" stroke="currentColor" stroke-width="2" stroke-linecap="round" stroke-linejoin="round">' + DRAW_ICONS[k] + '</svg>';
34282
+ if (DRAW_MODES.indexOf(k) >= 0 || k === 'hole') {
34283
+ b.setAttribute('aria-pressed', self.mode === k ? 'true' : 'false');
34284
+ b.addEventListener('click', function () { if (self.mode === k) { self.cancel(); } else { self.start(k); } });
34285
+ } else if (k === 'delete') {
34286
+ b.disabled = !self.selected;
34287
+ b.addEventListener('click', function () { self.delete(); });
34288
+ } else {
34289
+ b.disabled = k === 'undo' ? !self.undoStack.length : !self.redoStack.length;
34290
+ b.addEventListener('click', function () { self[k](); });
34291
+ }
34292
+ el.appendChild(b);
34293
+ });
34294
+ };
34295
+
34296
+ /**
34297
+ * Selects features by drawing on the map: 'box' (press and drag) or 'lasso' (press and draw a free shape). Resolves
34298
+ * with { features: { layerId: [features] }, geometry } once the shape is drawn, or null when Escape cancels it.
34299
+ * A point (or custom marker) counts when it is inside; a line or area when any of its vertices is.
34300
+ * @param {Object} [o] mode ('box' default, 'lasso'), layers (default every point, custom marker, line and area layer)
34301
+ */
34302
+ SMap.prototype.selectArea = function (o) {
34303
+ o = o || {};
34304
+ var self = this;
34305
+ var mode = o.mode === 'lasso' ? 'lasso' : 'box';
34306
+ return this.ready.then(function () {
34307
+ return new Promise(function (resolve) {
34308
+ var m = self.engine;
34309
+ var overlay = self._markerOverlay(), doc = overlay.ownerDocument;
34310
+ var svgNs = 'http://www.w3.org/2000/svg';
34311
+ var svg = doc.createElementNS(svgNs, 'svg');
34312
+ svg.setAttribute('class', 'smap-select');
34313
+ var shape = doc.createElementNS(svgNs, mode === 'box' ? 'rect' : 'polyline');
34314
+ svg.appendChild(shape);
34315
+ var points = null, panWasOn = !!(m.dragPan && (!m.dragPan.isEnabled || m.dragPan.isEnabled()));
34316
+ if (panWasOn) { m.dragPan.disable(); }
34317
+ if (m.boxZoom && m.boxZoom.disable) { m.boxZoom.disable(); }
34318
+ m.getCanvas().style.cursor = 'crosshair';
34319
+ var finish = function (result) {
34320
+ m.off('mousedown', down); m.off('mousemove', move); m.off('mouseup', up);
34321
+ m.off('touchstart', down); m.off('touchmove', move); m.off('touchend', up);
34322
+ m.getContainer().removeEventListener('keydown', key);
34323
+ if (svg.parentNode) { svg.parentNode.removeChild(svg); }
34324
+ if (panWasOn) { m.dragPan.enable(); }
34325
+ if (m.boxZoom && m.boxZoom.enable) { m.boxZoom.enable(); }
34326
+ m.getCanvas().style.cursor = '';
34327
+ resolve(result);
34328
+ };
34329
+ var draw = function () {
34330
+ if (mode === 'box') {
34331
+ var a = points[0], b = points[points.length - 1];
34332
+ shape.setAttribute('x', Math.min(a.x, b.x)); shape.setAttribute('y', Math.min(a.y, b.y));
34333
+ shape.setAttribute('width', Math.abs(a.x - b.x)); shape.setAttribute('height', Math.abs(a.y - b.y));
34334
+ } else {
34335
+ shape.setAttribute('points', points.map(function (p) { return p.x + ',' + p.y; }).join(' '));
34336
+ }
34337
+ };
34338
+ var down = function (e) { e.preventDefault(); points = [e.point]; overlay.appendChild(svg); draw(); };
34339
+ var move = function (e) { if (!points) { return; } if (mode === 'box') { points = [points[0], e.point]; } else { points.push(e.point); } draw(); };
34340
+ var up = function (e) {
34341
+ if (!points) { return; }
34342
+ if (mode === 'box') { points = [points[0], e.point]; }
34343
+ var ring;
34344
+ if (mode === 'box') {
34345
+ var a = points[0], b = points[1];
34346
+ ring = [[a.x, a.y], [b.x, a.y], [b.x, b.y], [a.x, b.y]];
34347
+ } else {
34348
+ ring = points.map(function (p) { return [p.x, p.y]; });
34349
+ }
34350
+ var geoRing = ring.map(function (p) { var ll = m.unproject(p); return [ll.lng, ll.lat]; });
34351
+ var geometry = { type: 'Polygon', coordinates: [closeRing(geoRing)] };
34352
+ finish({ features: self._featuresIn(ring, o.layers), geometry: geometry });
34353
+ };
34354
+ var key = function (ev) { if (ev.key === 'Escape') { finish(null); } };
34355
+ m.on('mousedown', down); m.on('mousemove', move); m.on('mouseup', up);
34356
+ m.on('touchstart', down); m.on('touchmove', move); m.on('touchend', up);
34357
+ m.getContainer().addEventListener('keydown', key);
34358
+ });
34359
+ });
34360
+ };
34361
+
34362
+ // The features of the map's layers with a vertex inside a ring of screen points (projected now).
34363
+ SMap.prototype._featuresIn = function (ring, layers) {
34364
+ var self = this, m = this.engine, out = {};
34365
+ var xs = ring.map(function (p) { return p[0]; }), ys = ring.map(function (p) { return p[1]; });
34366
+ var minX = Math.min.apply(null, xs), maxX = Math.max.apply(null, xs), minY = Math.min.apply(null, ys), maxY = Math.max.apply(null, ys);
34367
+ var inside = function (c) {
34368
+ var p = m.project(c);
34369
+ if (p.x < minX || p.x > maxX || p.y < minY || p.y > maxY) { return false; }
34370
+ return interop.geo.pointInPolygon([p.x, p.y], ring);
34371
+ };
34372
+ (layers || this._order).forEach(function (id) {
34373
+ var def = self._layers[id];
34374
+ if (!def || def.hidden || !def.data || ['points', 'custom', 'lines', 'polygons', 'heatmap'].indexOf(def.kind) < 0) { return; }
34375
+ var hits = def.data.features.filter(function (f) {
34376
+ var found = false;
34377
+ (function walk(c) { if (found || !c) { return; } if (typeof c[0] === 'number') { found = inside(c); } else { c.forEach(walk); } })(f.geometry && f.geometry.coordinates);
34378
+ return found;
34379
+ });
34380
+ if (hits.length) { out[id] = hits; }
34381
+ });
34382
+ return out;
34383
+ };
34384
+
34385
+ // ------------------------------------------------------------------ controls (G8): own controls, base imagery, layer switcher
34386
+
34387
+ /**
34388
+ * Puts an element or an engine control in a corner of the map without making it a tool (it is never hidden by the
34389
+ * tools control). An element returns where the page had it when removed.
34390
+ * @param {Element|Object} target
34391
+ * @param {string} [position] 'top-left', 'top-right' (default), 'bottom-left', 'bottom-right'
34392
+ */
34393
+ SMap.prototype.addControl = function (target, position) {
34394
+ position = position || 'top-right';
34395
+ if (TOOL_CORNERS.indexOf(position) < 0) { throw new Error('sMap: unknown control position "' + position + '"'); }
34396
+ if (!isElement(target) && !(target && typeof target.onAdd === 'function')) { throw new Error('sMap: a control is an element or an engine control'); }
34397
+ this._controls = this._controls || [];
34398
+ var holder = { position: position, el: null };
34399
+ var control = isElement(target) ? elementControl(holder, target) : target;
34400
+ this._controls.push({ target: target, control: control, position: position });
34401
+ var self = this;
34402
+ if (this.engine) { this.engine.addControl(control, position); } else { this.ready.then(function () { self.engine.addControl(control, position); }); }
34403
+ return this;
34404
+ };
34405
+
34406
+ SMap.prototype.removeControl = function (target) {
34407
+ var list = this._controls || [];
34408
+ for (var i = 0; i < list.length; i++) {
34409
+ if (list[i].target !== target) { continue; }
34410
+ if (this.engine) { this.engine.removeControl(list[i].control); }
34411
+ list.splice(i, 1);
34412
+ break;
34413
+ }
34414
+ return this;
34415
+ };
34416
+
34417
+ var BASE_RASTER = 'smap-base-imagery';
34418
+
34419
+ /**
34420
+ * Imagery (satellite, aerial, a scanned map, …) in place of the street map: raster tiles drawn over the basemap's
34421
+ * land, water and roads, under its labels — which stay with `labels: true` (a hybrid map) and are hidden otherwise.
34422
+ * Your layers stay on top, in their slots. null goes back to the street map.
34423
+ * @param {Object|null} imagery { tiles: [url with {z}/{x}/{y}], tileSize (256), minzoom, maxzoom, attribution,
34424
+ * scheme ('xyz' | 'tms'), labels (default false) }
34425
+ */
34426
+ SMap.prototype.setBaseImagery = function (imagery) {
34427
+ if (imagery && (!Array.isArray(imagery.tiles) || !imagery.tiles.length)) { throw new Error('sMap: base imagery needs tiles'); }
34428
+ // Google's and Bing's tiles only through their own terms: Google's with setGoogleBase (M31, M72).
34429
+ if (imagery) { interop.refuseForbidden(imagery.tiles); }
34430
+ return this._setBaseImagery(imagery);
34431
+ };
34432
+
34433
+ SMap.prototype._setBaseImagery = function (imagery) {
34434
+ this._baseImagery = imagery ? Object.assign({}, imagery) : null;
34435
+ if (this.engine && this._styleReady) { this._applyBaseImagery(); }
34436
+ return this;
34437
+ };
34438
+
34439
+ // Whether a style (a scheme, 'custom:<id>', a URL or an object) is the one shown now.
34440
+ SMap.prototype._isStyle = function (style) {
34441
+ if (typeof style === 'string' && FLAVORS.indexOf(style) >= 0) { return !this._customStyle && !this._serverStyle && this._flavor === style; }
34442
+ if (typeof style === 'string' && style.indexOf(CUSTOM_PREFIX) === 0) { return this._serverStyle === style; }
34443
+ return this._customStyle === style;
34444
+ };
34445
+
34446
+ SMap.prototype.baseImagery = function () { return this._baseImagery ? Object.assign({}, this._baseImagery) : null; };
34447
+
34448
+ SMap.prototype._applyBaseImagery = function () {
34449
+ var m = this.engine, b = this._baseImagery;
34450
+ if (m.getLayer(BASE_RASTER)) { m.removeLayer(BASE_RASTER); }
34451
+ if (m.getSource(BASE_RASTER)) { m.removeSource(BASE_RASTER); }
34452
+ var anchors = this.slots();
34453
+ var labelsAt = anchors.labels;
34454
+ // The basemap's labels: every basemap layer from where the labels slot begins.
34455
+ var ids = this._basemapIds.filter(function (x) { return m.getLayer(x); });
34456
+ var from = labelsAt ? ids.indexOf(labelsAt) : -1;
34457
+ var labelIds = from >= 0 ? ids.slice(from) : [];
34458
+ var hidden = this._imageryHid || [];
34459
+ hidden.forEach(function (x) { if (m.getLayer(x)) { m.setLayoutProperty(x, 'visibility', 'visible'); } });
34460
+ this._imageryHid = [];
34461
+ if (!b) { return; }
34462
+ var source = { type: 'raster', tiles: b.tiles.slice(), tileSize: b.tileSize || 256 };
34463
+ if (b.minzoom !== undefined) { source.minzoom = b.minzoom; }
34464
+ if (b.maxzoom !== undefined) { source.maxzoom = b.maxzoom; }
34465
+ if (b.attribution) { source.attribution = b.attribution; }
34466
+ if (b.scheme) { source.scheme = b.scheme; }
34467
+ m.addSource(BASE_RASTER, source);
34468
+ m.addLayer({ id: BASE_RASTER, type: 'raster', source: BASE_RASTER }, labelsAt || undefined);
34469
+ if (!b.labels) {
34470
+ var self = this;
34471
+ labelIds.forEach(function (x) {
34472
+ if (m.getLayoutProperty && m.getLayoutProperty(x, 'visibility') === 'none') { return; }
34473
+ m.setLayoutProperty(x, 'visibility', 'none');
34474
+ self._imageryHid.push(x);
34475
+ });
34476
+ }
34477
+ };
34478
+
34479
+ // ---- 3D models (G12): glTF models at points, drawn with three.js (handed over once with sMap.useThree)
34480
+
34481
+
34482
+ /**
34483
+ * glTF models at points (vehicles, buildings, equipment), drawn in the map's 3D view and turned to each feature's
34484
+ * heading. Needs three.js: call sMap.useThree(THREE, GLTFLoader) once first.
34485
+ * @param {Object} o model (a .glb / .gltf URL), size (metres per model unit, default 1; or per feature),
34486
+ * heading (degrees clockwise from north, default 0; or per feature, e.g. { property: 'bearing' }),
34487
+ * altitude (metres above the ground, default 0), rotate ([x, y, z] degrees turning the model upright and to
34488
+ * face north before the heading; default [90, 0, 180], right for a model whose up is +Y and front +Z),
34489
+ * idProperty, minzoom, slot, before, zIndex
34490
+ */
34491
+ SMap.prototype.addModels = function (id, data, o) {
34492
+ if (!interop.getThree()) { throw new Error('sMap: call sMap.useThree(THREE, GLTFLoader) before addModels'); }
34493
+ if (!o || !o.model) { throw new Error('sMap: addModels needs a model URL'); }
34494
+ this._define(id, { kind: 'models', data: toFeatureCollection(data), o: o });
34495
+ return this;
34496
+ };
34497
+
34498
+ SMap.prototype._modelLayer = function (id, def) {
34499
+ var self = this, three = interop.getThree(), T = three.THREE, o = def.o;
34500
+ var deg = Math.PI / 180;
34501
+ var base = o.rotate || [90, 0, 180];
34502
+ var baseMatrix = new T.Matrix4().makeRotationFromEuler(new T.Euler(base[0] * deg, base[1] * deg, base[2] * deg, 'ZYX'));
34503
+ var layer = {
34504
+ id: 'smap-' + id + '-models', type: 'custom', renderingMode: '3d',
34505
+ onAdd: function (map, gl) {
34506
+ this.map = map;
34507
+ this.scene = new T.Scene();
34508
+ this.camera = new T.Camera();
34509
+ this.renderer = new T.WebGLRenderer({ canvas: map.getCanvas(), context: gl, antialias: true });
34510
+ this.renderer.autoClear = false;
34511
+ this.scene.add(new T.AmbientLight(0xffffff, 0.8));
34512
+ var sun = new T.DirectionalLight(0xffffff, 0.6);
34513
+ sun.position.set(0.3, -0.5, 1);
34514
+ this.scene.add(sun);
34515
+ this.objects = {};
34516
+ var me = this;
34517
+ new three.GLTFLoader().load(o.model, function (gltf) {
34518
+ me.prototypeObject = gltf.scene;
34519
+ map.triggerRepaint();
34520
+ }, undefined, function (error) { self._reportError(error); });
34521
+ },
34522
+ render: function (gl, args) {
34523
+ if (!this.prototypeObject) { return; }
34524
+ var matrix = args && args.defaultProjectionData ? args.defaultProjectionData.mainMatrix : (args && args.modelViewProjectionMatrix) || args;
34525
+ var seen = {}, me = this, cur = self._layers[id];
34526
+ if (!cur) { return; }
34527
+ cur.data.features.forEach(function (f, i) {
34528
+ var at = pointOf(f);
34529
+ if (!at) { return; }
34530
+ var key = featureKey(cur, f, i);
34531
+ seen[key] = true;
34532
+ var obj = me.objects[key];
34533
+ if (!obj) { obj = me.objects[key] = me.prototypeObject.clone(true); obj.matrixAutoUpdate = false; me.scene.add(obj); }
34534
+ var props = f.properties || {};
34535
+ var mc = engine.MercatorCoordinate.fromLngLat(at, +plainValue(o.altitude, props, f, 0) || 0);
34536
+ var k = mc.meterInMercatorCoordinateUnits() * (+plainValue(o.size, props, f, 1) || 1);
34537
+ var heading = (+plainValue(o.heading, props, f, 0) || 0) * deg;
34538
+ obj.matrix.copy(new T.Matrix4().makeTranslation(mc.x, mc.y, mc.z)
34539
+ .multiply(new T.Matrix4().makeScale(k, -k, k))
34540
+ .multiply(new T.Matrix4().makeRotationZ(heading))
34541
+ .multiply(baseMatrix));
34542
+ obj.matrixWorldNeedsUpdate = true;
34543
+ });
34544
+ Object.keys(this.objects).forEach(function (key) { if (!seen[key]) { me.scene.remove(me.objects[key]); delete me.objects[key]; } });
34545
+ this.camera.projectionMatrix = new T.Matrix4().fromArray(matrix);
34546
+ this.renderer.resetState();
34547
+ this.renderer.render(this.scene, this.camera);
34548
+ },
34549
+ onRemove: function () { if (this.renderer && this.renderer.dispose) { this.renderer.dispose(); } },
34550
+ };
34551
+ return layer;
34552
+ };
34553
+
34554
+ var GOOGLE_LOGO = 'https://maps.gstatic.com/mapfiles/api-3/images/google_white5.png';
34555
+
34556
+ /**
34557
+ * Google's base maps from the Map Tiles API (G10), read straight from Google with a session your server made with
34558
+ * your own Google key; shown in place of the street map like setBaseImagery. As Google's terms ask, the Google logo
34559
+ * is shown and the copyright of the area in view is asked of Google after each move. null takes it off.
34560
+ * @param {Object|null} g { session, key } (or `tiles`: the tile URL template, and `viewport`: the viewport address up
34561
+ * to its query, both with session and key), type ('roadmap' | 'satellite', for the attribution only),
34562
+ * maxzoom (22), labels (keep the street map's labels over Google's imagery; default false),
34563
+ * onFail() (called when Google's first tiles fail and none loads: show your own map instead)
34564
+ */
34565
+ SMap.prototype.setGoogleBase = function (g) {
34566
+ var self = this;
34567
+ var run = function () {
34568
+ var m = self.engine;
34569
+ if (self._google) {
34570
+ if (self._google.control) { m.removeControl(self._google.control); }
34571
+ self._google.off.forEach(function (x) { m.off(x[0], x[1]); });
34572
+ self._google = null;
34573
+ }
34574
+ if (!g) { self._setBaseImagery(null); return; }
34575
+ if (!g.tiles && !(g.session && g.key)) { throw new Error('sMap: a Google layer needs session and key, or tiles'); }
34576
+ var q = g.session ? 'session=' + encodeURIComponent(g.session) + '&key=' + encodeURIComponent(g.key) : '';
34577
+ var tiles = g.tiles || 'https://tile.googleapis.com/v1/2dtiles/{z}/{x}/{y}?' + q;
34578
+ var viewport = g.viewport || (q ? 'https://tile.googleapis.com/tile/v1/viewport?' + q : null);
34579
+ var state = { off: [], control: null, text: null, errors: 0, loaded: 0, failed: false };
34580
+ self._google = state;
34581
+ self._setBaseImagery({ tiles: [tiles], tileSize: 256, maxzoom: g.maxzoom || 22, labels: !!g.labels });
34582
+ // The logo and the copyright of the area in view, bottom left.
34583
+ var doc = m.getContainer().ownerDocument;
34584
+ var box = doc.createElement('div');
34585
+ box.className = 'smap-google';
34586
+ var logo = doc.createElement('img');
34587
+ logo.src = GOOGLE_LOGO;
34588
+ logo.alt = 'Google';
34589
+ var text = doc.createElement('span');
34590
+ text.className = 'smap-google-copyright';
34591
+ text.textContent = 'Google';
34592
+ box.appendChild(logo);
34593
+ box.appendChild(text);
34594
+ state.text = text;
34595
+ state.control = { onAdd: function () { return box; }, onRemove: function () { if (box.parentNode) { box.parentNode.removeChild(box); } } };
34596
+ m.addControl(state.control, 'bottom-left');
34597
+ var seq = 0;
34598
+ var copyright = function () {
34599
+ if (!viewport || self._google !== state || typeof fetch !== 'function') { return; }
34600
+ var b = m.getBounds(), mine = ++seq;
34601
+ var url = viewport + (viewport.indexOf('?') >= 0 ? '&' : '?') + 'zoom=' + Math.round(m.getZoom() + 1) +
34602
+ '&north=' + b.getNorth() + '&south=' + b.getSouth() + '&east=' + b.getEast() + '&west=' + b.getWest();
34603
+ fetch(url).then(function (r) { return r.ok ? r.json() : null; }).then(function (v) {
34604
+ if (mine === seq && self._google === state) { text.textContent = (v && v.copyright) || 'Google'; }
34605
+ }, function () {});
34606
+ };
34607
+ var watch = function (e) {
34608
+ if (!e || e.sourceId !== BASE_RASTER || state.failed) { return; }
34609
+ if (e.type === 'error') { state.errors += 1; } else if (e.tile) { state.loaded += 1; }
34610
+ if (state.errors >= 4 && state.loaded === 0) {
34611
+ state.failed = true;
34612
+ if (g.onFail) { g.onFail(); }
34613
+ }
34614
+ };
34615
+ m.on('moveend', copyright); state.off.push(['moveend', copyright]);
34616
+ m.on('error', watch); state.off.push(['error', watch]);
34617
+ m.on('sourcedata', watch); state.off.push(['sourcedata', watch]);
34618
+ copyright();
34619
+ };
34620
+ if (this.engine) { run(); } else { this.ready.then(run); }
34621
+ return this;
34622
+ };
34623
+
34624
+ var LAYERS_ICON = '<svg viewBox="0 0 24 24" width="18" height="18" aria-hidden="true" focusable="false" fill="none" ' +
34625
+ 'stroke="currentColor" stroke-width="2" stroke-linejoin="round"><path d="M12 3 2 8l10 5 10-5-10-5z"/>' +
34626
+ '<path d="m2 13 10 5 10-5"/></svg>';
34627
+
34628
+ /**
34629
+ * The layer switcher: one button opening a list of base maps (one at a time) and overlays (each on or off).
34630
+ * base: [{ id, label, style? (a scheme, 'custom:…' or a style URL), imagery? (as setBaseImagery) }]
34631
+ * overlays: [{ id, label, layers: [layer ids], visible? }]
34632
+ * value (the base shown at first), title (the button's label), onChange({ base, overlays: [ids shown] })
34633
+ */
34634
+ function layersControl(map, opts) {
34635
+ var base = opts.base || [];
34636
+ var overlays = opts.overlays || [];
34637
+ var current = opts.value || (base[0] && base[0].id) || null;
34638
+ var shown = {};
34639
+ overlays.forEach(function (ov) { shown[ov.id] = ov.visible !== false; });
34640
+ var el = null, button = null, panel = null;
34641
+ function report() {
34642
+ if (opts.onChange) { opts.onChange({ base: current, overlays: overlays.filter(function (ov) { return shown[ov.id]; }).map(function (ov) { return ov.id; }) }); }
34643
+ }
34644
+ function applyBase(entry) {
34645
+ if (!entry) { return; }
34646
+ // The scheme already shown is not loaded again (no flicker when only the imagery changes).
34647
+ if (entry.style !== undefined && entry.style !== null && !map._isStyle(entry.style)) { map.setStyle(entry.style); }
34648
+ map.setBaseImagery(entry.imagery || null);
34649
+ }
34650
+ function applyOverlay(ov) { (ov.layers || []).forEach(function (id) { map.setVisible(id, !!shown[ov.id]); }); }
34651
+ function render() {
34652
+ var doc = el.ownerDocument;
34653
+ while (panel.firstChild) { panel.removeChild(panel.firstChild); }
34654
+ var name = 'smap-base-' + Math.random().toString(36).slice(2);
34655
+ base.forEach(function (entry) {
34656
+ var row = doc.createElement('label');
34657
+ row.className = 'smap-layers-row';
34658
+ var input = doc.createElement('input');
34659
+ input.type = 'radio'; input.name = name; input.value = entry.id; input.checked = entry.id === current;
34660
+ input.addEventListener('change', function () { current = entry.id; applyBase(entry); report(); });
34661
+ row.appendChild(input);
34662
+ row.appendChild(doc.createTextNode(' ' + (entry.label || entry.id)));
34663
+ panel.appendChild(row);
34664
+ });
34665
+ if (base.length && overlays.length) { var hr = doc.createElement('div'); hr.className = 'smap-layers-sep'; panel.appendChild(hr); }
34666
+ overlays.forEach(function (ov) {
34667
+ var row = doc.createElement('label');
34668
+ row.className = 'smap-layers-row';
34669
+ var input = doc.createElement('input');
34670
+ input.type = 'checkbox'; input.value = ov.id; input.checked = !!shown[ov.id];
34671
+ input.addEventListener('change', function () { shown[ov.id] = input.checked; applyOverlay(ov); report(); });
34672
+ row.appendChild(input);
34673
+ row.appendChild(doc.createTextNode(' ' + (ov.label || ov.id)));
34674
+ panel.appendChild(row);
34675
+ });
34676
+ }
34677
+ function open(on) { panel.hidden = !on; button.setAttribute('aria-expanded', on ? 'true' : 'false'); }
34678
+ function close() { if (panel && !panel.hidden) { open(false); } }
34679
+ return {
34680
+ onAdd: function (m) {
34681
+ var doc = m.getContainer().ownerDocument;
34682
+ el = doc.createElement('div');
34683
+ el.className = 'maplibregl-ctrl maplibregl-ctrl-group smap-layers';
34684
+ button = doc.createElement('button');
34685
+ button.type = 'button';
34686
+ button.className = 'smap-layers-button';
34687
+ button.innerHTML = LAYERS_ICON;
34688
+ button.title = opts.title || 'Layers';
34689
+ button.setAttribute('aria-label', opts.title || 'Layers');
34690
+ button.setAttribute('aria-haspopup', 'true');
34691
+ button.addEventListener('click', function () { open(panel.hidden); });
34692
+ panel = doc.createElement('div');
34693
+ panel.className = 'smap-layers-panel';
34694
+ el.appendChild(button);
34695
+ el.appendChild(panel);
34696
+ render();
34697
+ open(false);
34698
+ m.on('click', close);
34699
+ // The starting state: the chosen base and every overlay as given.
34700
+ var entry = base.filter(function (b) { return b.id === current; })[0];
34701
+ if (entry && entry.imagery) { map.setBaseImagery(entry.imagery); }
34702
+ overlays.forEach(function (ov) { if (!shown[ov.id]) { applyOverlay(ov); } });
34703
+ return el;
34704
+ },
34705
+ onRemove: function (m) { m.off('click', close); if (el && el.parentNode) { el.parentNode.removeChild(el); } el = null; },
34706
+ };
34707
+ }
34708
+
31457
34709
  // ------------------------------------------------------------------ plan editor (OPEN-ROUTE-EDIT E10)
31458
34710
 
31459
34711
  /**
@@ -31973,7 +35225,9 @@ function smapCreateSdk(engine, interop, plan) {
31973
35225
  var out = { type: 'smap.layers', version: 1 };
31974
35226
  if (!this._customStyle) { out.basemap = { style: this._serverStyle || this._flavor, language: this._language, overrides: clone(this._basemapOverrides) }; }
31975
35227
  if (this._sourceOrder.length) { out.sources = this.sources(); }
31976
- out.layers = this._order.map(function (id) {
35228
+ // The shared description has points, lines, areas and style layers; custom markers, heat maps and 3D models are
35229
+ // not part of it and are left out.
35230
+ out.layers = this._order.filter(function (id) { return ['points', 'lines', 'polygons', 'style'].indexOf(self._layers[id].kind) >= 0; }).map(function (id) {
31977
35231
  var def = self._layers[id];
31978
35232
  var e = { id: id, kind: def.kind };
31979
35233
  if (def.slot) { e.slot = def.slot; }
@@ -32032,7 +35286,8 @@ function smapCreateSdk(engine, interop, plan) {
32032
35286
  def.slot = o.slot || null;
32033
35287
  def.before = o.before || null;
32034
35288
  def.popupFn = typeof o.popup === 'string' ? popupTemplate(o.popup) : null;
32035
- def.zIndex = def.o.zIndex || 0;
35289
+ // A layer's place among layers; a per-feature zIndex (custom markers) orders within the layer only.
35290
+ def.zIndex = typeof def.o.zIndex === 'number' ? def.o.zIndex : 0;
32036
35291
  def.engineLayers = [];
32037
35292
  if (this._layerToolHides(id)) { def.hidden = true; }
32038
35293
  this._layers[id] = def;
@@ -32091,6 +35346,10 @@ function smapCreateSdk(engine, interop, plan) {
32091
35346
 
32092
35347
  SMap.prototype._drop = function (id, def) {
32093
35348
  var m = this.engine;
35349
+ if (def.kind === 'custom') { this._dropCustom(id, def); return; }
35350
+ if (this._ghost && this._ghost.id === id && m) { this._dropGhost(id); }
35351
+ if (this._tooltipFor && this._tooltipFor.id === id) { this._hideTooltip(); }
35352
+ if (def.clusterSet) { this._dropCustom(id + ':clusters', def.clusterSet); def.clusterSet = null; }
32094
35353
  if (!m) { return; }
32095
35354
  def.engineLayers.forEach(function (l) { if (m.getLayer(l)) { m.removeLayer(l); } });
32096
35355
  if (def.kind !== 'style' && m.getSource('smap-' + id)) { m.removeSource('smap-' + id); }
@@ -32110,13 +35369,24 @@ function smapCreateSdk(engine, interop, plan) {
32110
35369
  Object.keys(this._basemapEdits).forEach(function (id) { self._applyEdits(id, self._basemapEdits[id]); });
32111
35370
  this._sourceOrder.forEach(function (id) { if (!m.getSource(id)) { self._engineSource(id); } });
32112
35371
  this._applyBuildings();
35372
+ this._imageryHid = [];
35373
+ if (this._baseImagery) { this._applyBaseImagery(); }
35374
+ if (this._terrain) { this._applyTerrain(); }
32113
35375
  this._order.forEach(function (id) { self._add(id, self._layers[id]); });
32114
35376
  };
32115
35377
 
32116
35378
  SMap.prototype._add = function (id, def) {
32117
35379
  var m = this.engine;
32118
35380
  var o = def.o;
35381
+ if (def.kind === 'custom') { this._addCustom(id, def); return; }
32119
35382
  var before = this._beforeId(id);
35383
+ if (def.kind === 'models') {
35384
+ var modelLayer = this._modelLayer(id, def);
35385
+ if (o.minzoom !== undefined) { modelLayer.minzoom = o.minzoom; }
35386
+ m.addLayer(modelLayer, before);
35387
+ def.engineLayers.push(modelLayer.id);
35388
+ return;
35389
+ }
32120
35390
  if (def.kind === 'style') {
32121
35391
  // Passed to the engine as it is (a copy, so the engine never holds the object you gave).
32122
35392
  var styleLayer = clone(def.layer);
@@ -32132,6 +35402,8 @@ function smapCreateSdk(engine, interop, plan) {
32132
35402
  if (o.maxzoom !== undefined) { range.maxzoom = o.maxzoom; }
32133
35403
  var visibility = def.hidden ? 'none' : 'visible';
32134
35404
  var source = { type: 'geojson', data: def.data, promoteId: o.idProperty };
35405
+ // A dragged point is found again by its place in the data (unless idProperty names it).
35406
+ if (def.kind === 'points' && o.draggable && !o.idProperty) { source.generateId = true; }
32135
35407
  if (def.kind === 'points' && o.cluster) {
32136
35408
  source.cluster = true;
32137
35409
  source.clusterRadius = (o.cluster && o.cluster.radius) || 50;
@@ -32154,7 +35426,8 @@ function smapCreateSdk(engine, interop, plan) {
32154
35426
  var color = o.color || '#4f46e5';
32155
35427
  var main;
32156
35428
  if (def.kind === 'points') {
32157
- if (o.cluster) {
35429
+ var htmlClusters = o.cluster && (o.cluster.html || o.cluster.ring);
35430
+ if (o.cluster && !htmlClusters) {
32158
35431
  add({
32159
35432
  id: src + '-clusters', type: 'circle', filter: ['has', 'point_count'],
32160
35433
  paint: {
@@ -32175,6 +35448,7 @@ function smapCreateSdk(engine, interop, plan) {
32175
35448
  });
32176
35449
  });
32177
35450
  }
35451
+ if (htmlClusters) { this._htmlClusters(id, def, src); }
32178
35452
  var only = o.cluster ? ['!', ['has', 'point_count']] : undefined;
32179
35453
  var both = function (extra) { return only ? ['all', only, extra] : extra; };
32180
35454
  if (o.marker) {
@@ -32192,13 +35466,31 @@ function smapCreateSdk(engine, interop, plan) {
32192
35466
  // Opacity of the pin, its number and its badge together (the route map draws settled stops at .72).
32193
35467
  var markerPaint = mk.opacity !== undefined ? { 'icon-opacity': valueExpr(mk.opacity, 1) } : undefined;
32194
35468
  main = src + '-points';
32195
- // From bakeZoom on (default 13) a pin's number is drawn into its own image, so an upper pin covers a lower
32196
- // one completely. Further out, where thousands of pins can be in view, the numbers stay one layer above the
32197
- // pins (an image per colour pair instead of per pin and number). bakeZoom: false keeps them separate.
35469
+ // A pin's number and count badge are drawn into its own image (as one element of the route map's pins), so an
35470
+ // upper pin covers a lower one completely, number and badge included. bakeZoom (a zoom) keeps them their own
35471
+ // layers above the pins further out than it — fewer images where thousands of pins are in view, but numbers
35472
+ // over every pin there — and bakeZoom: false keeps them apart at every zoom. textMinzoom / badgeMinzoom start
35473
+ // them at their zoom either way.
32198
35474
  var plainPin = drawnImageId('pin', [shape, str(mk.fill, '#ffffff'), str(mk.border, color), String(bw), String(size)]);
32199
- var bakeZoom = mk.text !== undefined && mk.bakeZoom !== false ? (mk.bakeZoom !== undefined ? mk.bakeZoom : 13) : null;
32200
- var pinImage = bakeZoom === null ? plainPin : ['step', ['zoom'], plainPin, bakeZoom,
32201
- drawnImageId('pinnum', [shape, str(mk.fill, '#ffffff'), str(mk.border, color), String(bw), String(size), str(mk.textColor, '#ffffff'), str(mk.text, '')])];
35475
+ var hasText = mk.text !== undefined, hasBadge = mk.badge !== undefined;
35476
+ var bakeZoom = (hasText || hasBadge) && mk.bakeZoom !== false ? (typeof mk.bakeZoom === 'number' ? mk.bakeZoom : 0) : null;
35477
+ var badgeNumber = ['to-number', valueExpr(mk.badge, 0), 0];
35478
+ var textMin = typeof mk.textMinzoom === 'number' ? mk.textMinzoom : 0;
35479
+ var badgeMin = typeof mk.badgeMinzoom === 'number' ? mk.badgeMinzoom : 0;
35480
+ var imageAt = function (z) {
35481
+ if (bakeZoom === null || z < bakeZoom) { return plainPin; }
35482
+ var withText = hasText && z >= textMin, withBadge = hasBadge && z >= badgeMin;
35483
+ if (!withText && !withBadge) { return plainPin; }
35484
+ return drawnImageId('pinnum', [shape, str(mk.fill, '#ffffff'), str(mk.border, color), String(bw), String(size), str(mk.textColor, '#ffffff'),
35485
+ withBadge ? ['case', ['>', badgeNumber, 1], ['to-string', badgeNumber], ''] : '', withText ? str(mk.text, '') : '']);
35486
+ };
35487
+ var breaks = [bakeZoom, textMin, badgeMin].filter(function (z, i, all) { return typeof z === 'number' && z > 0 && all.indexOf(z) === i; })
35488
+ .sort(function (x, y) { return x - y; });
35489
+ var pinImage = imageAt(0);
35490
+ if (breaks.length) {
35491
+ pinImage = ['step', ['zoom'], imageAt(0)];
35492
+ breaks.forEach(function (z) { pinImage.push(z, imageAt(z)); });
35493
+ }
32202
35494
  var markerSpecs = [];
32203
35495
  var addMarker = function (layer) { markerSpecs.push(JSON.parse(JSON.stringify(layer))); add(layer); };
32204
35496
  addMarker({
@@ -32211,7 +35503,7 @@ function smapCreateSdk(engine, interop, plan) {
32211
35503
  'icon-allow-overlap': true, 'icon-ignore-placement': true,
32212
35504
  },
32213
35505
  });
32214
- if (mk.text !== undefined) {
35506
+ if (hasText && bakeZoom !== 0) {
32215
35507
  var text = str(mk.text, '');
32216
35508
  addMarker({
32217
35509
  id: src + '-numbers', type: 'symbol', filter: both(['!=', text, '']), minzoom: mk.textMinzoom, maxzoom: bakeZoom === null ? undefined : bakeZoom, paint: markerPaint,
@@ -32221,10 +35513,10 @@ function smapCreateSdk(engine, interop, plan) {
32221
35513
  },
32222
35514
  });
32223
35515
  }
32224
- if (mk.badge !== undefined) {
32225
- var badge = ['to-number', valueExpr(mk.badge, 0), 0];
35516
+ if (hasBadge && bakeZoom !== 0) {
35517
+ var badge = badgeNumber;
32226
35518
  addMarker({
32227
- id: src + '-badges', type: 'symbol', filter: both(['>', badge, 1]), minzoom: mk.badgeMinzoom, paint: markerPaint,
35519
+ id: src + '-badges', type: 'symbol', filter: both(['>', badge, 1]), minzoom: mk.badgeMinzoom, maxzoom: bakeZoom === null ? undefined : bakeZoom, paint: markerPaint,
32228
35520
  layout: {
32229
35521
  'icon-image': drawnImageId('badge', [['to-string', badge]]),
32230
35522
  'icon-offset': g.badge, 'icon-size': scale,
@@ -32269,6 +35561,30 @@ function smapCreateSdk(engine, interop, plan) {
32269
35561
  paint: { 'text-color': '#1f2937', 'text-halo-color': '#ffffff', 'text-halo-width': 1.4 },
32270
35562
  });
32271
35563
  }
35564
+ } else if (def.kind === 'heatmap') {
35565
+ main = src + '-heat';
35566
+ var hc = o.colors;
35567
+ var ramp = Array.isArray(hc) && hc.length && Array.isArray(hc[0]) ? hc : null;
35568
+ var colorExpr = ['interpolate', ['linear'], ['heatmap-density']];
35569
+ if (ramp) { ramp.forEach(function (st) { colorExpr.push(st[0], st[1]); }); }
35570
+ else if (Array.isArray(hc) && hc.length) {
35571
+ // Colours from low to high: transparent at no density, then evenly spaced.
35572
+ colorExpr.push(0, 'rgba(0, 0, 0, 0)');
35573
+ hc.forEach(function (c, i) { colorExpr.push((i + 1) / hc.length, c); });
35574
+ } else {
35575
+ colorExpr.push(0, 'rgba(33, 102, 172, 0)', 0.2, 'rgb(103, 169, 207)', 0.4, 'rgb(209, 229, 240)', 0.6, 'rgb(253, 219, 199)', 0.8, 'rgb(239, 138, 98)', 1, 'rgb(178, 24, 43)');
35576
+ }
35577
+ var weight = o.weight === undefined ? 1 : (typeof o.weight === 'number' ? o.weight : ['to-number', valueExpr(o.weight, 1), 1]);
35578
+ add({
35579
+ id: main, type: 'heatmap',
35580
+ paint: {
35581
+ 'heatmap-weight': weight,
35582
+ 'heatmap-radius': o.radius === undefined ? 20 : o.radius,
35583
+ 'heatmap-intensity': o.intensity === undefined ? 1 : o.intensity,
35584
+ 'heatmap-opacity': o.opacity === undefined ? 0.8 : o.opacity,
35585
+ 'heatmap-color': colorExpr,
35586
+ },
35587
+ });
32272
35588
  } else if (def.kind === 'lines') {
32273
35589
  main = src + '-lines';
32274
35590
  // simplestyle (stroke, stroke-width, stroke-opacity) when the layer gives no colour of its own
@@ -32293,6 +35609,15 @@ function smapCreateSdk(engine, interop, plan) {
32293
35609
  };
32294
35610
  if (o.dash) { paint['line-dasharray'] = o.dash; }
32295
35611
  add({ id: main, type: 'line', layout: round, paint: paint });
35612
+ if (o.label) {
35613
+ // A permanent label along the line (a route's name), repeated along long lines.
35614
+ add({
35615
+ id: src + '-labels', type: 'symbol',
35616
+ layout: { 'symbol-placement': 'line', 'symbol-spacing': o.labelSpacing || 250, 'text-field': ['to-string', ['get', o.label]],
35617
+ 'text-font': ['Noto Sans Medium'], 'text-size': 12, 'text-keep-upright': true },
35618
+ paint: { 'text-color': valueExpr(o.labelColor, '#1f2937'), 'text-halo-color': '#ffffff', 'text-halo-width': 1.6 },
35619
+ });
35620
+ }
32296
35621
  if (o.arrows) {
32297
35622
  var ar = o.arrows === true ? {} : o.arrows;
32298
35623
  var arrowSize = ar.size || 14;
@@ -32335,7 +35660,9 @@ function smapCreateSdk(engine, interop, plan) {
32335
35660
  }
32336
35661
  // The popup is opened by the map's one click handler (_popupClick), from this layer's own hit test.
32337
35662
  def.popupLayer = o.popup ? main : null;
32338
- if (main && (o.popup || o.onClick)) {
35663
+ if (main && o.tooltip) { this._tooltips(id, def, main); }
35664
+ if (main && def.kind === 'points' && o.draggable) { this._dragPoints(id, def, main); }
35665
+ if (main && (o.popup || o.onClick || o.draggable)) {
32339
35666
  if (o.onClick) {
32340
35667
  this._listen(id, 'click', main, function (e) { o.onClick(e.features[0], e); });
32341
35668
  }
@@ -32406,6 +35733,8 @@ function smapCreateSdk(engine, interop, plan) {
32406
35733
  slots: SLOTS.slice(),
32407
35734
  formats: interop.formats,
32408
35735
  convert: interop.convert,
35736
+ geo: interop.geo,
35737
+ useThree: interop.useThree,
32409
35738
  rasterUrl: interop.rasterUrl,
32410
35739
  rasterTileJsonUrl: interop.rasterTileJsonUrl,
32411
35740
  styleUrl: interop.styleUrl,
@@ -32423,5 +35752,5 @@ function smapCreateSdk(engine, interop, plan) {
32423
35752
 
32424
35753
  return module.exports;
32425
35754
  }
32426
- (typeof globalThis !== 'undefined' ? globalThis : window).sMap = smapCreateSdk(smapCreateEngine(), smapCreateInterop(), smapCreatePlan());
35755
+ (typeof globalThis !== 'undefined' ? globalThis : window).sMap = smapCreateSdk(smapCreateEngine(), smapCreateInterop(), smapCreateCanvas(), smapCreatePlan());
32427
35756
  })();