@superrouteca/smap 1.1.6 → 1.2.0

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.6. Bundles maplibre-gl 6.16.0 (BSD-3-Clause), see vendor-licenses.txt. */
1
+ /*! sMap Web SDK 1.2.0. 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 (M61): 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;
@@ -28361,6 +29825,24 @@ function smapCreatePlan() {
28361
29825
  // its Origin; a native app also names itself with X-SMap-App (and X-SMap-App-Cert on Android).
28362
29826
 
28363
29827
  var DEFAULT_BASE = 'https://open.superroute.ca';
29828
+ // The sMap service a map key's configuration is read from (GET <smap>/plan/v1/config), unless the editor is told another.
29829
+ var DEFAULT_SMAP = 'https://tile.srsr.ca';
29830
+ // Fast path (OPEN-ROUTE-EDIT E19, §2f.5): a call there not answered within this long is repeated on the standard path.
29831
+ // Per call, in this one place: every call 2 s, except refine (its search runs up to 2 s inside sRoad, and sMap's own
29832
+ // refine budget is 4 s) 5 s.
29833
+ var FAST_PATH_TIMEOUT_MS = 2000;
29834
+ var FAST_PATH_REFINE_TIMEOUT_MS = 5000;
29835
+ /** The fast-path time limit of a call (`path` after /v1/plan), from the defaults or the options that replace them. */
29836
+ function fastPathTimeoutFor(path, o) {
29837
+ var refine = path === '/refine';
29838
+ var given = refine ? o.fastPathRefineTimeout : o.fastPathTimeout;
29839
+ if (typeof given === 'number' && given > 0) { return given; }
29840
+ return refine ? FAST_PATH_REFINE_TIMEOUT_MS : FAST_PATH_TIMEOUT_MS;
29841
+ }
29842
+ // A map key's configuration is kept this long; one that could not be read is asked for again after RETRY.
29843
+ var KEY_CONFIG_TTL_MS = 600000;
29844
+ var KEY_CONFIG_RETRY_MS = 60000;
29845
+ var PLAN_PREFIX = '/v1/plan';
28364
29846
  // A token whose expiry can be read is renewed this many seconds before it ends.
28365
29847
  var RENEW_BEFORE = 30;
28366
29848
  var TOKEN_PREFIX = 'sr_pet_';
@@ -28383,19 +29865,27 @@ function smapCreatePlan() {
28383
29865
  /**
28384
29866
  * What a token provider gave: the token string, or the token answer of POST /v1/plan/token
28385
29867
  * ({ access_token, token_type, expires_in, expires_at, scopes, origins }, or that answer's `{ data }` envelope).
28386
- * Returns { token, exp } with exp in Unix seconds (0 when it cannot be told).
29868
+ * Returns { token, exp, fastPath } with exp in Unix seconds (0 when it cannot be told) and fastPath the answer's
29869
+ * `fast_path.url` (null without one: every call goes to the standard path).
28387
29870
  */
28388
29871
  function readToken(t) {
28389
29872
  if (t && typeof t === 'object' && t.data && typeof t.data === 'object' && !t.access_token) { t = t.data; }
28390
- if (typeof t === 'string' && t) { return { token: t, exp: tokenExpiry(t) }; }
29873
+ if (typeof t === 'string' && t) { return { token: t, exp: tokenExpiry(t), fastPath: null }; }
28391
29874
  if (t && typeof t === 'object' && typeof t.access_token === 'string' && t.access_token) {
28392
29875
  var exp = t.expires_at ? Date.parse(t.expires_at) / 1000 : 0;
28393
29876
  if (!exp && typeof t.expires_in === 'number') { exp = Date.now() / 1000 + t.expires_in; }
28394
- return { token: t.access_token, exp: exp || tokenExpiry(t.access_token) };
29877
+ return { token: t.access_token, exp: exp || tokenExpiry(t.access_token), fastPath: fastPathOf(t) };
28395
29878
  }
28396
29879
  return null;
28397
29880
  }
28398
29881
 
29882
+ /** The fast-path address of a token answer or a map key's configuration (`fast_path.url`), or null. */
29883
+ function fastPathOf(o) {
29884
+ var f = o && typeof o === 'object' ? o.fast_path : null;
29885
+ var url = f && typeof f === 'object' && typeof f.url === 'string' ? f.url.replace(/\/+$/, '') : '';
29886
+ return url ? url : null;
29887
+ }
29888
+
28399
29889
  /** The app headers of a native app: options.app is 'android:<package>' / 'apple:<bundle id>' / 'windows:<id>', or { id, cert }. */
28400
29890
  function appHeaders(app) {
28401
29891
  var h = {};
@@ -28414,6 +29904,7 @@ function smapCreatePlan() {
28414
29904
  if (c && typeof c.token === 'function') {
28415
29905
  var token = null;
28416
29906
  var exp = 0;
29907
+ var fast = null;
28417
29908
  var pending = null;
28418
29909
  var fetchToken = function () {
28419
29910
  if (!pending) {
@@ -28423,6 +29914,7 @@ function smapCreatePlan() {
28423
29914
  if (!read) { throw new Error('sMap plan editor: the token provider gave no token'); }
28424
29915
  token = read.token;
28425
29916
  exp = read.exp;
29917
+ fast = read.fastPath;
28426
29918
  return token;
28427
29919
  }, function (e) { pending = null; throw e; });
28428
29920
  }
@@ -28436,6 +29928,8 @@ function smapCreatePlan() {
28436
29928
  },
28437
29929
  // After a 401 SESSION_EXPIRED: forget the token so the next call asks the provider again. True when a retry may help.
28438
29930
  renew: function () { token = null; exp = 0; return true; },
29931
+ // The fast-path address the latest token answer gave (read after headers()), or null.
29932
+ fastPath: function () { return Promise.resolve(fast); },
28439
29933
  };
28440
29934
  }
28441
29935
  if (c && typeof c.key === 'string' && c.key) {
@@ -28443,6 +29937,7 @@ function smapCreatePlan() {
28443
29937
  kind: 'key',
28444
29938
  headers: function () { return Promise.resolve({ Authorization: 'Bearer ' + c.key }); },
28445
29939
  renew: function () { return false; },
29940
+ fastPath: null, // set by the transport: the key's configuration on sMap
28446
29941
  };
28447
29942
  }
28448
29943
  throw new Error('sMap plan editor: credentials are { token: () => Promise<string | TokenAnswer> } or { key: string }');
@@ -28465,44 +29960,155 @@ function smapCreatePlan() {
28465
29960
  function cancelled() { var e = new Error('cancelled'); e.name = 'AbortError'; e.cancelled = true; return e; }
28466
29961
 
28467
29962
  /**
28468
- * The transport: send(method, path, body, signal) resolves { status, body, data, matrix } (matrix: the X-Plan-Matrix
28469
- * header) or rejects with a PlanError. A 401 SESSION_EXPIRED with a token provider asks for a new token and repeats
28470
- * the call once; every other refusal (SESSION_REVOKED, TOKEN_INVALID, 403 NOT_AUTHORIZED with its reason) is raised.
29963
+ * The transport: send(method, path, body, signal) resolves { status, body, data, matrix, path } (matrix: the
29964
+ * X-Plan-Matrix header; path: 'fast' or 'standard', where the answer came from) or rejects with a PlanError. A 401
29965
+ * SESSION_EXPIRED with a token provider asks for a new token and repeats the call once; every other refusal
29966
+ * (SESSION_REVOKED, TOKEN_INVALID, 403 NOT_AUTHORIZED with its reason) is raised.
29967
+ *
29968
+ * Fast path (OPEN-ROUTE-EDIT E19, §2f.5): when the credential names a fast-path address (the token answer's
29969
+ * `fast_path.url`, or a map key's configuration from GET <smapUrl>/plan/v1/config), each call goes to
29970
+ * <url>/<same path> with the same method, credential, headers and body. A 409 USE_STANDARD_PATH (or the header
29971
+ * X-Plan-Path: standard), any 5xx, a network error or no answer within 2 s (refine: 5 s) repeats the same call once on the standard
29972
+ * path (<baseUrl>/v1/plan/<same path>); the next call tries the fast path again. 402, 429 and every other 4xx are final.
28471
29973
  */
28472
29974
  function createTransport(o) {
28473
29975
  o = o || {};
28474
29976
  var base = String(o.baseUrl || DEFAULT_BASE).replace(/\/$/, '');
29977
+ var smap = String(o.smapUrl || DEFAULT_SMAP).replace(/\/$/, '');
29978
+ var fastOn = o.fastPath !== false;
29979
+ var timeoutMs = fastPathTimeoutFor('', o);
28475
29980
  var creds = credentialsOf(o.credentials);
28476
29981
  var app = appHeaders(o.app);
28477
29982
  var fetchFn = o.fetch || (typeof fetch === 'function' ? function (url, init) { return fetch(url, init); } : null);
28478
29983
  if (!fetchFn) { throw new Error('sMap plan editor: no fetch; pass options.fetch'); }
28479
29984
 
29985
+ function headersWith(h, json) {
29986
+ var headers = { Accept: 'application/json' };
29987
+ Object.keys(app).forEach(function (k) { headers[k] = app[k]; });
29988
+ Object.keys(h).forEach(function (k) { headers[k] = h[k]; });
29989
+ if (json) { headers['Content-Type'] = 'application/json'; }
29990
+ return headers;
29991
+ }
29992
+
29993
+ // One request, read to the end. With `limit` it gives up after that many ms ({ timedOut: true }); a network error
29994
+ // resolves { failed: error } unless the caller's own signal ended it (then it rejects, cancelled).
29995
+ function exchange(url, init, signal, limit) {
29996
+ if (!limit) {
29997
+ return fetchFn(url, init).then(read);
29998
+ }
29999
+ var inner = newController();
30000
+ var timedOut = false;
30001
+ var timer = null;
30002
+ var onAbort = function () { if (inner) { inner.abort(); } };
30003
+ if (signal) {
30004
+ if (signal.aborted) { return Promise.reject(cancelled()); }
30005
+ if (signal.addEventListener) { signal.addEventListener('abort', onAbort); }
30006
+ }
30007
+ var own = {};
30008
+ Object.keys(init).forEach(function (k) { own[k] = init[k]; });
30009
+ if (inner) { own.signal = inner.signal; }
30010
+ var done = function () {
30011
+ if (timer) { clearTimeout(timer); }
30012
+ if (signal && signal.removeEventListener) { signal.removeEventListener('abort', onAbort); }
30013
+ };
30014
+ var timeout = new Promise(function (resolve) {
30015
+ timer = setTimeout(function () { timedOut = true; if (inner) { inner.abort(); } resolve({ timedOut: true }); }, limit);
30016
+ });
30017
+ var answer = Promise.resolve().then(function () { return fetchFn(url, own); }).then(read).then(function (r) { return r; }, function (e) {
30018
+ if (signal && signal.aborted) { throw cancelled(); }
30019
+ if (timedOut) { return { timedOut: true }; }
30020
+ return { failed: e };
30021
+ });
30022
+ return Promise.race([answer, timeout]).then(function (r) {
30023
+ done();
30024
+ if (signal && signal.aborted) { throw cancelled(); }
30025
+ return r;
30026
+ }, function (e) { done(); throw e; });
30027
+ }
30028
+
30029
+ function read(res) {
30030
+ return res.text().then(function (text) {
30031
+ var json = null;
30032
+ try { json = text ? JSON.parse(text) : null; } catch (e) { json = null; }
30033
+ var get = function (k) { return res.headers && typeof res.headers.get === 'function' ? res.headers.get(k) : null; };
30034
+ return { status: res.status, ok: res.ok, json: json, matrix: get('X-Plan-Matrix'), planPath: get('X-Plan-Path') };
30035
+ });
30036
+ }
30037
+
30038
+ // A map key's configuration on sMap: GET <smap>/plan/v1/config -> {"fast_path": {"url"}} or {}.
30039
+ var keyConfig = { url: null, until: 0, pending: null };
30040
+ function keyFastPath(h) {
30041
+ if (Date.now() < keyConfig.until) { return Promise.resolve(keyConfig.url); }
30042
+ if (keyConfig.pending) { return keyConfig.pending; }
30043
+ keyConfig.pending = exchange(smap + '/plan/v1/config', { method: 'GET', headers: headersWith(h, false) }, null, timeoutMs).then(function (r) {
30044
+ if (r.status >= 200 && r.status < 300) {
30045
+ keyConfig.url = fastPathOf(r.json);
30046
+ keyConfig.until = Date.now() + KEY_CONFIG_TTL_MS;
30047
+ } else {
30048
+ // A refusal is an answer (no fast path for this key); a failure is asked again after a minute.
30049
+ keyConfig.url = null;
30050
+ keyConfig.until = Date.now() + (r.status >= 400 && r.status < 500 ? KEY_CONFIG_TTL_MS : KEY_CONFIG_RETRY_MS);
30051
+ }
30052
+ return keyConfig.url;
30053
+ }, function () {
30054
+ keyConfig.url = null;
30055
+ keyConfig.until = Date.now() + KEY_CONFIG_RETRY_MS;
30056
+ return null;
30057
+ }).then(function (url) { keyConfig.pending = null; return url; });
30058
+ return keyConfig.pending;
30059
+ }
30060
+
30061
+ function fastPathFor(h) {
30062
+ if (!fastOn) { return Promise.resolve(null); }
30063
+ return creds.fastPath ? creds.fastPath() : keyFastPath(h);
30064
+ }
30065
+
30066
+ // Repeat on the standard path (§2f.5)?
30067
+ function useStandard(r) {
30068
+ if (r.timedOut || r.failed) { return true; }
30069
+ if (r.status >= 500) { return true; }
30070
+ if (r.status !== 409) { return false; }
30071
+ return !!(r.json && r.json.error && r.json.error.code === 'USE_STANDARD_PATH') || String(r.planPath || '').toLowerCase() === 'standard';
30072
+ }
30073
+
28480
30074
  function send(method, path, body, signal, retried) {
28481
- return creds.headers().then(function (h) {
28482
- var headers = { Accept: 'application/json' };
28483
- Object.keys(app).forEach(function (k) { headers[k] = app[k]; });
28484
- Object.keys(h).forEach(function (k) { headers[k] = h[k]; });
28485
- var init = { method: method, headers: headers };
28486
- if (body !== undefined) { headers['Content-Type'] = 'application/json'; init.body = JSON.stringify(body); }
28487
- if (signal) { init.signal = signal; }
28488
- return fetchFn(base + path, init);
28489
- }).then(function (res) {
28490
- return res.text().then(function (text) {
28491
- var json = null;
28492
- try { json = text ? JSON.parse(text) : null; } catch (e) { json = null; }
28493
- var matrix = res.headers && typeof res.headers.get === 'function' ? res.headers.get('X-Plan-Matrix') : null;
28494
- if (!res.ok) {
28495
- var err = (json && json.error) || {};
28496
- if (res.status === 401 && err.code === 'SESSION_EXPIRED' && !retried && creds.renew()) { return send(method, path, body, signal, true); }
28497
- throw PlanError(err.message || ('HTTP ' + res.status), {
28498
- status: res.status, code: err.code || null, details: err.details || null, reason: err.reason || (json && json.reason) || null, path: path,
28499
- });
28500
- }
28501
- return { status: res.status, body: json, data: json && json.data, matrix: matrix };
30075
+ var h = null;
30076
+ return creds.headers().then(function (got) {
30077
+ h = got;
30078
+ return fastPathFor(h);
30079
+ }).then(function (fast) {
30080
+ if (signal && signal.aborted) { throw cancelled(); }
30081
+ var init = { method: method, headers: headersWith(h, body !== undefined) };
30082
+ if (body !== undefined) { init.body = JSON.stringify(body); }
30083
+ var standard = function () {
30084
+ var s = {};
30085
+ Object.keys(init).forEach(function (k) { s[k] = init[k]; });
30086
+ s.headers = headersWith(h, body !== undefined);
30087
+ if (signal) { s.signal = signal; }
30088
+ return exchange(base + path, s, signal, 0).then(function (r) { r.via = 'standard'; return r; });
30089
+ };
30090
+ if (!fast || path.indexOf(PLAN_PREFIX + '/') !== 0) { return standard(); }
30091
+ var rest = path.slice(PLAN_PREFIX.length);
30092
+ return exchange(fast + rest, init, signal, fastPathTimeoutFor(rest, o)).then(function (r) {
30093
+ if (useStandard(r)) { return standard(); }
30094
+ r.via = 'fast';
30095
+ return r;
28502
30096
  });
30097
+ }).then(function (r) {
30098
+ if (!r.ok) {
30099
+ var json = r.json;
30100
+ var err = (json && json.error) || {};
30101
+ if (r.status === 401 && err.code === 'SESSION_EXPIRED' && !retried && creds.renew()) { return send(method, path, body, signal, true); }
30102
+ var e = PlanError(err.message || ('HTTP ' + r.status), {
30103
+ status: r.status, code: err.code || null, details: err.details || null, reason: err.reason || (json && json.reason) || null, path: path,
30104
+ });
30105
+ e.via = r.via;
30106
+ throw e;
30107
+ }
30108
+ return { status: r.status, body: r.json, data: r.json && r.json.data, matrix: r.matrix, path: r.via };
28503
30109
  });
28504
30110
  }
28505
- return { send: send, kind: creds.kind, baseUrl: base };
30111
+ return { send: send, kind: creds.kind, baseUrl: base, smapUrl: smap };
28506
30112
  }
28507
30113
 
28508
30114
  // ------------------------------------------------------------------ plans
@@ -28655,7 +30261,12 @@ function smapCreatePlan() {
28655
30261
  * @param {Object} options
28656
30262
  * @param {Object} options.credentials { token: () => Promise<string | TokenAnswer> } or { key: string }
28657
30263
  * @param {string|Object} [options.app] a native app's identity: 'android:<package>' / 'apple:<bundle id>' / 'windows:<id>', or { id, cert }
28658
- * @param {string} [options.baseUrl] the Open Platform (default https://open.superroute.ca)
30264
+ * @param {string} [options.baseUrl] the Open Platform (default https://open.superroute.ca): the standard path
30265
+ * @param {string} [options.smapUrl] the sMap service a map key's configuration is read from (default
30266
+ * https://tile.srsr.ca; map.planEditor passes the map's own sMap address)
30267
+ * @param {boolean} [options.fastPath=true] use the fast path when the credential names one (false: standard only)
30268
+ * @param {number} [options.fastPathTimeout=2000] ms a fast-path call may take before it is repeated on the standard path
30269
+ * @param {number} [options.fastPathRefineTimeout=5000] the same for refine (its search takes longer)
28659
30270
  * @param {Function} [options.fetch] fetch to use (default the page's)
28660
30271
  * @param {Object} [options.plan] the starting plan: { vehicles, jobs, routes, region?, profile?, departed_at? }
28661
30272
  * @param {string} [options.region] used when the plan names none
@@ -28691,6 +30302,7 @@ function smapCreatePlan() {
28691
30302
  this._opening = null;
28692
30303
  this._openingKey = null;
28693
30304
  this._matrixRetryAt = 0;
30305
+ this._path = null;
28694
30306
  this._destroyed = false;
28695
30307
  if (options.plan) { this.setPlan(options.plan).catch(function () {}); }
28696
30308
  }
@@ -28759,7 +30371,7 @@ function smapCreatePlan() {
28759
30371
  return {
28760
30372
  plan: this.getPlan(), result: this.getResult(), busy: this._busy, error: this._error, canUndo: this.canUndo(),
28761
30373
  canRedo: this.canRedo(), choices: clone(this._choices), locked: this.locked(), last: clone(this._last),
28762
- preview: this._previewResult ? clone(this._previewResult) : null,
30374
+ preview: this._previewResult ? clone(this._previewResult) : null, path: this._path,
28763
30375
  };
28764
30376
  };
28765
30377
 
@@ -28969,7 +30581,7 @@ function smapCreatePlan() {
28969
30581
  var e = this._history[this._at] || {};
28970
30582
  this._emit('change', {
28971
30583
  kind: kind, plan: this.getPlan(), result: this.getResult(), answer: this._last ? clone(this._last.answer) : null,
28972
- pending: !e.result, canUndo: this.canUndo(), canRedo: this.canRedo(),
30584
+ pending: !e.result, canUndo: this.canUndo(), canRedo: this.canRedo(), path: this._path,
28973
30585
  });
28974
30586
  };
28975
30587
 
@@ -29069,7 +30681,7 @@ function smapCreatePlan() {
29069
30681
  self._error = null;
29070
30682
  self._setBusy(false);
29071
30683
  if (self._history[self._at] === target || kind !== 'recost') { self._changed(kind); }
29072
- return { kind: kind, plan: self.getPlan(), result: self.getResult(), answer: clone(answer) };
30684
+ return { kind: kind, plan: self.getPlan(), result: self.getResult(), answer: clone(answer), path: self._path };
29073
30685
  }, function (err) {
29074
30686
  var current = self._inflight === ticket;
29075
30687
  if (current) { self._inflight = null; self._setBusy(false); }
@@ -29100,6 +30712,7 @@ function smapCreatePlan() {
29100
30712
  if (matrix) { body.matrix = matrix; } else { delete body.matrix; }
29101
30713
  return self._transport.send('POST', path, body, signal);
29102
30714
  }).then(function (res) {
30715
+ if (!self._destroyed) { self._path = res.path || null; }
29103
30716
  if (body.matrix) { self._snapshotSeen(res.matrix, body.matrix); }
29104
30717
  return res;
29105
30718
  }, function (err) {
@@ -29151,7 +30764,7 @@ function smapCreatePlan() {
29151
30764
  }
29152
30765
  self._matrixRetryAt = 0;
29153
30766
  if (self._openingKey === key) { self._matrix = id; self._matrixKey = key; }
29154
- self._emit('snapshot', { status: 'opened', matrix: id, expires_at: res.data.expires_at || null, node: res.data.node || null });
30767
+ self._emit('snapshot', { status: 'opened', matrix: id, expires_at: res.data.expires_at || null, node: res.data.node || null, path: res.path || null });
29155
30768
  return id;
29156
30769
  }, function (err) {
29157
30770
  self._matrixRetryAt = Date.now() + SNAPSHOT_RETRY_MS;
@@ -29887,7 +31500,7 @@ function smapCreatePlan() {
29887
31500
  */
29888
31501
  function attach(map, options) {
29889
31502
  options = options || {};
29890
- var editor = new PlanEditor(Object.assign({}, options, { plan: null }));
31503
+ var editor = new PlanEditor(Object.assign({}, options, { plan: null, smapUrl: options.smapUrl || map._base }));
29891
31504
  var layer = attachToMap(map, editor, options);
29892
31505
  var toolId = null;
29893
31506
  var destroyed = false;
@@ -29947,12 +31560,12 @@ function smapCreatePlan() {
29947
31560
 
29948
31561
  return module.exports;
29949
31562
  }
29950
- function smapCreateSdk(engine, interop, plan) {
31563
+ function smapCreateSdk(engine, interop, canvas, plan) {
29951
31564
  var module = { exports: {} };
29952
31565
  var exports = module.exports;
29953
31566
  var define;
29954
31567
  var require = function (name) { throw new Error('sMap: unexpected require of ' + name); };
29955
- var self = { maplibregl: engine, smapInterop: interop, smapPlan: plan };
31568
+ var self = { maplibregl: engine, smapInterop: interop, smapCanvas: canvas, smapPlan: plan };
29956
31569
  /*!
29957
31570
  * sMap Web SDK — maps from Superroute's sMap service.
29958
31571
  *
@@ -29966,14 +31579,15 @@ function smapCreateSdk(engine, interop, plan) {
29966
31579
  if (typeof module === 'object' && module.exports) {
29967
31580
  module.exports = factory(root.maplibregl !== undefined ? root.maplibregl : require('maplibre-gl'),
29968
31581
  root.smapInterop !== undefined ? root.smapInterop : require('./smap-interop.js'),
31582
+ root.smapCanvas !== undefined ? root.smapCanvas : (typeof require === 'function' ? require('./smap-canvas.js') : null),
29969
31583
  root.smapPlan !== undefined ? root.smapPlan : (typeof require === 'function' ? require('./smap-plan.js') : null));
29970
31584
  } else {
29971
- root.sMap = factory(root.maplibregl, root.smapInterop, root.smapPlan);
31585
+ root.sMap = factory(root.maplibregl, root.smapInterop, root.smapCanvas, root.smapPlan);
29972
31586
  }
29973
- })(typeof self !== 'undefined' ? self : this, function (engine, interop, plan) {
31587
+ })(typeof self !== 'undefined' ? self : this, function (engine, interop, canvasLib, plan) {
29974
31588
  'use strict';
29975
31589
 
29976
- var VERSION = '1.1.6';
31590
+ var VERSION = '1.2.0';
29977
31591
  var FLAVORS = ['light', 'white', 'grayscale', 'dark', 'black'];
29978
31592
  var BASEMAP_SOURCE = 'basemap';
29979
31593
  var BUILDINGS_LAYER = 'smap-buildings-3d';
@@ -30384,12 +31998,14 @@ function smapCreateSdk(engine, interop, plan) {
30384
31998
  * @param {Object} [options.popup] default popup options of every layer and openPopup (className, maxWidth,
30385
31999
  * minWidth, offset, anchor, closeButton, closeOnClick, focusAfterOpen)
30386
32000
  * @param {string|Node} [options.popupLoading] shown while a popup's content is a pending promise (default: dots)
32001
+ * @param {'auto'|'webgl'|'canvas'} [options.renderer] 'auto' (default): the WebGL map, or the canvas map (raster
32002
+ * tiles, layers drawn in 2D) where the browser has no WebGL 2 (M61)
30387
32003
  * Every other option (center, zoom, pitch, bearing, minZoom, maxZoom, maxBounds, hash, …) goes to the engine.
30388
32004
  */
30389
32005
  function SMap(options) {
30390
32006
  if (!(this instanceof SMap)) { return new SMap(options); }
30391
32007
  options = options || {};
30392
- if (!engine) { throw new Error('sMap: the rendering engine is not loaded'); }
32008
+ if (!engine && !canvasLib) { throw new Error('sMap: the rendering engine is not loaded'); }
30393
32009
  this._base = (options.baseUrl || DEFAULT_BASE).replace(/\/$/, '');
30394
32010
  this._token = options.token || null;
30395
32011
  this._getToken = options.getToken || null;
@@ -30439,9 +32055,16 @@ function smapCreateSdk(engine, interop, plan) {
30439
32055
  this._toolHandlers = [];
30440
32056
 
30441
32057
  var self = this;
32058
+ // The renderer (M61): the WebGL engine, or the canvas map where there is no WebGL 2 (or when asked for).
32059
+ var want = options.renderer || 'auto';
32060
+ // Asked of the page itself; without a page (a server, a test) the WebGL engine is kept.
32061
+ var hasPage = typeof document !== 'undefined' && !!document && typeof document.createElement === 'function';
32062
+ var useCanvas = !!canvasLib && (want === 'canvas' || (want === 'auto' && (!engine || (hasPage && !canvasLib.webgl2Available(document)))));
32063
+ this._lib = useCanvas ? canvasLib : engine;
32064
+ this.renderer = useCanvas ? 'canvas' : 'webgl';
30442
32065
  var engineOptions = {};
30443
32066
  for (var k in options) {
30444
- if (Object.prototype.hasOwnProperty.call(options, k) && ['token', 'getToken', 'apiKey', 'style', 'language', 'baseUrl', 'projection', 'nearest', 'nodes', 'popup', 'popupLoading', 'autoZoom', 'keyboard3D', 'tools'].indexOf(k) < 0) {
32067
+ 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) {
30445
32068
  engineOptions[k] = options[k];
30446
32069
  }
30447
32070
  }
@@ -30449,6 +32072,11 @@ function smapCreateSdk(engine, interop, plan) {
30449
32072
  // The page's origin is its identity: no app header is sent from a browser. The key travels in the style URL
30450
32073
  // (the service carries it into the tile URLs) and, for a style given as a URL or an object, as a header.
30451
32074
  engineOptions.transformRequest = function (url) {
32075
+ // Tiles of the canvas map are images: the token rides in the query (sMap reads `token` there too).
32076
+ if (self.renderer === 'canvas') {
32077
+ if (self._token && url.indexOf(self._base) === 0 && !/[?&]token=/.test(url)) { url += (url.indexOf('?') >= 0 ? '&' : '?') + 'token=' + encodeURIComponent(self._token); }
32078
+ return { url: url };
32079
+ }
30452
32080
  if ((self._token || self._apiKey) && url.indexOf(self._base) === 0) {
30453
32081
  var headers = {};
30454
32082
  if (self._token) { headers.Authorization = 'Bearer ' + self._token; }
@@ -30466,8 +32094,17 @@ function smapCreateSdk(engine, interop, plan) {
30466
32094
  options.nearest === false ? Promise.resolve() : nearestNode(this._base, options.nodes).then(function (base) { self._base = base; })
30467
32095
  ]);
30468
32096
  this.ready = start.then(function () {
30469
- engineOptions.style = self._styleUrl();
30470
- self.engine = new engine.Map(engineOptions);
32097
+ engineOptions.style = self._engineStyle();
32098
+ try {
32099
+ self.engine = new self._lib.Map(engineOptions);
32100
+ } catch (error) {
32101
+ // A WebGL context the browser refuses (a blocked GPU, too many maps): the canvas map instead, when allowed.
32102
+ if (self.renderer !== 'webgl' || want !== 'auto' || !canvasLib) { throw error; }
32103
+ self._lib = canvasLib;
32104
+ self.renderer = 'canvas';
32105
+ engineOptions.style = self._engineStyle();
32106
+ self.engine = new canvasLib.Map(engineOptions);
32107
+ }
30471
32108
  deckCompat(self.engine);
30472
32109
  if (self.engine.addControl) {
30473
32110
  var badge = badgeControl();
@@ -30496,6 +32133,20 @@ function smapCreateSdk(engine, interop, plan) {
30496
32133
  else if (style) { this._customStyle = style; this._serverStyle = null; }
30497
32134
  };
30498
32135
 
32136
+ // The style handed to the renderer: the vector style, or for the canvas map sMap's raster tiles of the same scheme.
32137
+ SMap.prototype._engineStyle = function () {
32138
+ if (this.renderer !== 'canvas') { return this._styleUrl(); }
32139
+ if (this._customStyle && typeof this._customStyle === 'object') { return this._customStyle; }
32140
+ var name = this._serverStyle || this._flavor;
32141
+ var win = typeof window !== 'undefined' ? window : {};
32142
+ var tiles = interop.rasterUrl(name, { baseUrl: this._base, lang: this._language, apiKey: this._apiKey, retina: (win.devicePixelRatio || 1) > 1 });
32143
+ return {
32144
+ version: 8,
32145
+ sources: { 'smap-raster': { type: 'raster', tiles: [tiles], tileSize: 256, maxzoom: 19, attribution: '&copy; <a href="https://www.openstreetmap.org/copyright">OpenStreetMap</a>' } },
32146
+ layers: [{ id: 'smap-raster', type: 'raster', source: 'smap-raster' }],
32147
+ };
32148
+ };
32149
+
30499
32150
  SMap.prototype._styleUrl = function () {
30500
32151
  if (this._customStyle) { return this._customStyle; }
30501
32152
  if (this._serverStyle) { return interop.styleUrl(this._serverStyle, { baseUrl: this._base, lang: this._language, apiKey: this._apiKey }); }
@@ -30526,7 +32177,7 @@ function smapCreateSdk(engine, interop, plan) {
30526
32177
  SMap.prototype.setStyle = function (style) {
30527
32178
  this._takeStyle(style);
30528
32179
  this._styleReady = false;
30529
- this.engine.setStyle(this._styleUrl());
32180
+ this.engine.setStyle(this._engineStyle());
30530
32181
  this._styleClass();
30531
32182
  return this;
30532
32183
  };
@@ -30603,7 +32254,7 @@ function smapCreateSdk(engine, interop, plan) {
30603
32254
  var k = POPUP_OPTIONS[i];
30604
32255
  if (k !== 'className' && k !== 'minWidth' && k !== 'autoPan' && o[k] !== undefined) { engineOptions[k] = k === 'maxWidth' ? cssSize(o[k]) : o[k]; }
30605
32256
  }
30606
- var popup = new engine.Popup(engineOptions).setLngLat(lngLat);
32257
+ var popup = new this._lib.Popup(engineOptions).setLngLat(lngLat);
30607
32258
  this._popup = popup;
30608
32259
  var pending = isThenable(content);
30609
32260
  var loading = o.loading !== undefined ? o.loading : (this._popupLoading !== undefined ? this._popupLoading : POPUP_LOADING);
@@ -30655,12 +32306,14 @@ function smapCreateSdk(engine, interop, plan) {
30655
32306
 
30656
32307
  SMap.prototype._reportError = function (error) {
30657
32308
  var m = this.engine;
30658
- if (m && engine.ErrorEvent && m.fire) { m.fire(new engine.ErrorEvent(error)); } else if (typeof console !== 'undefined') { console.error(error); }
32309
+ if (m && this._lib.ErrorEvent && m.fire) { m.fire(new this._lib.ErrorEvent(error)); } else if (typeof console !== 'undefined') { console.error(error); }
30659
32310
  };
30660
32311
 
30661
32312
  // A click on the map: the top feature of the layers with a popup, if any, opens its layer's popup.
30662
32313
  SMap.prototype._popupClick = function (e) {
30663
32314
  var m = this.engine;
32315
+ // The release of a drag is not a click.
32316
+ if (this._dragEndedAt && Date.now() - this._dragEndedAt < 300) { return; }
30664
32317
  var ids = [];
30665
32318
  var byEngineLayer = {};
30666
32319
  for (var i = 0; i < this._order.length; i++) {
@@ -30787,7 +32440,7 @@ function smapCreateSdk(engine, interop, plan) {
30787
32440
  SMap.prototype.setLanguage = function (language) {
30788
32441
  this._language = language;
30789
32442
  // A scheme or a custom style of sMap is served per language; a style of your own keeps its labels.
30790
- if (!this._customStyle) { this._styleReady = false; this.engine.setStyle(this._styleUrl()); }
32443
+ if (!this._customStyle) { this._styleReady = false; this.engine.setStyle(this._engineStyle()); }
30791
32444
  return this;
30792
32445
  };
30793
32446
 
@@ -30902,6 +32555,8 @@ function smapCreateSdk(engine, interop, plan) {
30902
32555
  var def = this._layers[id];
30903
32556
  if (!def) { throw new Error('sMap: no layer ' + id); }
30904
32557
  def.data = toFeatureCollection(data);
32558
+ if (def.kind === 'custom') { this._customData(id, def); return this; }
32559
+ if (def.kind === 'models') { if (this.engine) { this.engine.triggerRepaint(); } return this; }
30905
32560
  if (def.hovered) { this._setHover(id, def, null); }
30906
32561
  var src = this.engine.getSource('smap-' + id);
30907
32562
  if (src) { src.setData(def.data); }
@@ -30913,6 +32568,8 @@ function smapCreateSdk(engine, interop, plan) {
30913
32568
  if (!def) { return this; }
30914
32569
  def.hidden = !visible;
30915
32570
  var m = this.engine;
32571
+ if (def.kind === 'custom') { if (!visible && this._tooltipFor && this._tooltipFor.id === id) { this._hideTooltip(); } this._layoutMarkers(); return this; }
32572
+ if (def.clusterSet) { this._layoutMarkers(); }
30916
32573
  if (!m) { return this; }
30917
32574
  def.engineLayers.forEach(function (l) { if (m.getLayer(l)) { m.setLayoutProperty(l, 'visibility', visible ? 'visible' : 'none'); } });
30918
32575
  return this;
@@ -30945,7 +32602,7 @@ function smapCreateSdk(engine, interop, plan) {
30945
32602
  SMap.prototype.fitLayer = function (id, options) {
30946
32603
  var def = this._layers[id];
30947
32604
  if (!def || !def.data.features.length) { return this; }
30948
- var b = new engine.LngLatBounds();
32605
+ var b = new this._lib.LngLatBounds();
30949
32606
  def.data.features.forEach(function extend(f) {
30950
32607
  (function walk(c) { if (typeof c[0] === 'number') { b.extend(c); } else { c.forEach(walk); } })(f.geometry.coordinates);
30951
32608
  });
@@ -30953,12 +32610,617 @@ function smapCreateSdk(engine, interop, plan) {
30953
32610
  return this;
30954
32611
  };
30955
32612
 
30956
- SMap.prototype.on = function () { this.engine.on.apply(this.engine, arguments); return this; };
30957
- SMap.prototype.off = function () { this.engine.off.apply(this.engine, arguments); return this; };
30958
- SMap.prototype.once = function () { return this.engine.once.apply(this.engine, arguments); };
30959
- SMap.prototype.flyTo = function (o) { this.engine.flyTo(o); return this; };
30960
- SMap.prototype.remove = function () { clearTimeout(this._refreshTimer); if (this.engine) { this.engine.remove(); } };
30961
-
32613
+ SMap.prototype.on = function () { this.engine.on.apply(this.engine, arguments); return this; };
32614
+ SMap.prototype.off = function () { this.engine.off.apply(this.engine, arguments); return this; };
32615
+ SMap.prototype.once = function () { return this.engine.once.apply(this.engine, arguments); };
32616
+ SMap.prototype.flyTo = function (o) { this.engine.flyTo(o); return this; };
32617
+ SMap.prototype.remove = function () { clearTimeout(this._refreshTimer); if (this.engine) { this.engine.remove(); } };
32618
+
32619
+ // ------------------------------------------------------------------ custom markers (G1), dragging (G2), tooltips (G5)
32620
+
32621
+ // A value that may differ per feature, read in JavaScript (custom markers, tooltips): a constant, a function of the
32622
+ // properties, or { property, default }. Engine expressions (arrays) are not read here and give the fallback.
32623
+ function plainValue(v, props, feature, fallback) {
32624
+ if (v === undefined || v === null) { return fallback; }
32625
+ if (typeof v === 'function') { var r = v(props || {}, feature); return r === undefined ? fallback : r; }
32626
+ if (Array.isArray(v)) { return fallback; }
32627
+ if (typeof v === 'object' && v.property) {
32628
+ var x = props ? props[v.property] : undefined;
32629
+ return x === undefined || x === null ? (v['default'] !== undefined ? v['default'] : fallback) : x;
32630
+ }
32631
+ return v;
32632
+ }
32633
+
32634
+ // Where an element's anchor sits, as the share of its own width and height to move it back by (CSS translate).
32635
+ var ANCHORS = {
32636
+ center: [-50, -50], top: [-50, 0], bottom: [-50, -100], left: [0, -50], right: [-100, -50],
32637
+ 'top-left': [0, 0], 'top-right': [-100, 0], 'bottom-left': [0, -100], 'bottom-right': [-100, -100],
32638
+ };
32639
+ // Pixels outside the map an element is still laid out in, so one entering the view is already there.
32640
+ var MARKER_MARGIN = 64;
32641
+ var DRAG_THRESHOLD = 3;
32642
+
32643
+ function featureKey(def, f, i) {
32644
+ var idp = def.o.idProperty;
32645
+ if (idp && f.properties && f.properties[idp] !== undefined && f.properties[idp] !== null) { return String(f.properties[idp]); }
32646
+ if (f.id !== undefined && f.id !== null) { return String(f.id); }
32647
+ return '#' + i;
32648
+ }
32649
+
32650
+ function pointOf(f) {
32651
+ var g = f && f.geometry;
32652
+ return g && g.type === 'Point' && Array.isArray(g.coordinates) && typeof g.coordinates[0] === 'number' ? g.coordinates : null;
32653
+ }
32654
+
32655
+ function offsetOf(v) {
32656
+ if (Array.isArray(v)) { return [+v[0] || 0, +v[1] || 0]; }
32657
+ if (typeof v === 'number') { return [0, -v]; }
32658
+ return [0, 0];
32659
+ }
32660
+
32661
+ // A feature's properties without its position (data given as {lng, lat, …} carries the position in them too), so a
32662
+ // marker that only moved is not rendered again.
32663
+ var POSITION_KEYS = { lng: 1, lat: 1, lon: 1, longitude: 1, latitude: 1, coordinates: 1 };
32664
+ function propsSignature(f) {
32665
+ var p = (f && f.properties) || {}, out = {};
32666
+ Object.keys(p).forEach(function (k) { if (!POSITION_KEYS[k]) { out[k] = p[k]; } });
32667
+ return JSON.stringify(out);
32668
+ }
32669
+
32670
+ /** A copy of a feature collection with one feature's point moved (the caller's own objects are never changed). */
32671
+ function movedCollection(fc, index, lngLat) {
32672
+ var features = fc.features.slice();
32673
+ var f = features[index];
32674
+ features[index] = Object.assign({}, f, { geometry: { type: 'Point', coordinates: [lngLat[0], lngLat[1]] } });
32675
+ return { type: 'FeatureCollection', features: features };
32676
+ }
32677
+
32678
+ /**
32679
+ * Custom markers: the caller's own element at each point — any HTML, laid out above the map's drawn layers. One
32680
+ * element per feature, made the first time the feature comes into view and moved while the map moves; features out
32681
+ * of view are not laid out, so thousands stay smooth.
32682
+ * @param {string} id
32683
+ * @param {Object|Array} data GeoJSON points, or an array of {lng, lat, …properties}
32684
+ * @param {Object} o
32685
+ * render(properties, feature) → an element or trusted HTML (inserted as is, never sanitized); required
32686
+ * anchor: 'center' (default), 'top', 'bottom', 'left', 'right', 'top-left', 'top-right', 'bottom-left', 'bottom-right'
32687
+ * offset: [x, y] pixels; className; opacity, zIndex (constants, functions of the properties or { property });
32688
+ * idProperty (the property naming each feature, else the feature's id, else its place in the data);
32689
+ * riseOnHover (the element under the pointer comes to the front); minzoom; maxzoom;
32690
+ * onClick(feature, event); popup (as on addPoints); tooltip, tooltipOptions (see addPoints);
32691
+ * draggable (true, or per feature), onDragStart / onDrag / onDragEnd(feature, { lngLat, point, originalEvent })
32692
+ */
32693
+ SMap.prototype.addCustomMarkers = function (id, data, o) {
32694
+ o = o || {};
32695
+ if (typeof o.render !== 'function') { throw new Error('sMap: custom markers need render(properties, feature)'); }
32696
+ if (o.anchor !== undefined && !ANCHORS[o.anchor]) { throw new Error('sMap: unknown anchor "' + o.anchor + '"'); }
32697
+ this._define(id, { kind: 'custom', data: toFeatureCollection(data), o: o });
32698
+ return this;
32699
+ };
32700
+
32701
+ /**
32702
+ * The element of one custom marker (made now if it was not in view yet), or null.
32703
+ * @param {string} id the layer
32704
+ * @param {string|number} key the feature's idProperty value, its id, or '#<index>'
32705
+ */
32706
+ SMap.prototype.getMarker = function (id, key) {
32707
+ var def = this._layers[id];
32708
+ if (!def || def.kind !== 'custom' || !def.custom) { return null; }
32709
+ var item = def.custom.byKey[String(key)];
32710
+ if (!item) { return null; }
32711
+ if (!item.el) { this._renderMarker(id, def, item); }
32712
+ return item.el;
32713
+ };
32714
+
32715
+ SMap.prototype._markerOverlay = function () {
32716
+ if (this._overlay && this._overlay.parentNode) { return this._overlay; }
32717
+ var m = this.engine;
32718
+ var host = m.getCanvasContainer ? m.getCanvasContainer() : m.getContainer();
32719
+ var doc = host.ownerDocument;
32720
+ var overlay = doc.createElement('div');
32721
+ overlay.className = 'smap-markers';
32722
+ // First in the canvas container after the canvas, so the engine's popups (added after it) stay on top.
32723
+ var canvas = m.getCanvas ? m.getCanvas() : null;
32724
+ if (canvas && canvas.parentNode === host) { host.insertBefore(overlay, canvas.nextSibling); } else { host.appendChild(overlay); }
32725
+ this._overlay = overlay;
32726
+ var self = this;
32727
+ if (!this._overlayBound) {
32728
+ this._overlayBound = true;
32729
+ var frame = null;
32730
+ var schedule = function () {
32731
+ if (frame !== null) { return; }
32732
+ var raf = typeof requestAnimationFrame === 'function' ? requestAnimationFrame : function (fn) { return setTimeout(fn, 16); };
32733
+ frame = raf(function () { frame = null; self._layoutMarkers(); });
32734
+ };
32735
+ this._scheduleLayout = schedule;
32736
+ m.on('move', function () { self._layoutMarkers(); });
32737
+ m.on('resize', schedule);
32738
+ m.on('zoomend', schedule);
32739
+ }
32740
+ return overlay;
32741
+ };
32742
+
32743
+ SMap.prototype._addCustom = function (id, def) {
32744
+ this._dropCustom(id, def);
32745
+ var items = [];
32746
+ var byKey = {};
32747
+ def.data.features.forEach(function (f, i) {
32748
+ var at = pointOf(f);
32749
+ if (!at) { return; }
32750
+ var item = { key: featureKey(def, f, i), index: i, f: f, el: null, shown: false, x: NaN, y: NaN, sig: null };
32751
+ items.push(item);
32752
+ byKey[item.key] = item;
32753
+ });
32754
+ def.custom = { items: items, byKey: byKey };
32755
+ this._markerOverlay();
32756
+ this._layoutMarkers();
32757
+ };
32758
+
32759
+ SMap.prototype._dropCustom = function (id, def) {
32760
+ var c = def.custom;
32761
+ if (!c) { return; }
32762
+ c.items.forEach(function (item) { if (item.el && item.el.parentNode) { item.el.parentNode.removeChild(item.el); } });
32763
+ def.custom = null;
32764
+ if (this._tooltipFor && this._tooltipFor.id === id) { this._hideTooltip(); }
32765
+ };
32766
+
32767
+ // New data for a custom marker layer: an element whose feature (by key) is still there is kept — moved when its point
32768
+ // moved, made again when its properties changed — so a marker being dragged or with its popup open stays the same.
32769
+ SMap.prototype._customData = function (id, def) {
32770
+ var old = def.custom;
32771
+ if (!old || !this.engine) { if (this.engine && this._styleReady) { this._addCustom(id, def); } return; }
32772
+ var items = [];
32773
+ var byKey = {};
32774
+ def.data.features.forEach(function (f, i) {
32775
+ if (!pointOf(f)) { return; }
32776
+ var key = featureKey(def, f, i);
32777
+ var item = old.byKey[key];
32778
+ if (item) {
32779
+ delete old.byKey[key];
32780
+ if (item.el && propsSignature(item.f) !== propsSignature(f)) { item.sig = null; }
32781
+ item.f = f;
32782
+ item.index = i;
32783
+ item.x = NaN;
32784
+ } else {
32785
+ item = { key: key, index: i, f: f, el: null, shown: false, x: NaN, y: NaN, sig: null };
32786
+ }
32787
+ items.push(item);
32788
+ byKey[key] = item;
32789
+ });
32790
+ Object.keys(old.byKey).forEach(function (k) { var gone = old.byKey[k]; if (gone.el && gone.el.parentNode) { gone.el.parentNode.removeChild(gone.el); } });
32791
+ def.custom = { items: items, byKey: byKey };
32792
+ this._layoutMarkers();
32793
+ };
32794
+
32795
+ SMap.prototype._renderMarker = function (id, def, item) {
32796
+ var self = this, o = def.o, doc = this._markerOverlay().ownerDocument;
32797
+ var el = item.el;
32798
+ if (!el) {
32799
+ el = doc.createElement('div');
32800
+ el.setAttribute('data-smap-layer', id);
32801
+ el.setAttribute('data-smap-key', item.key);
32802
+ item.el = el;
32803
+ this._bindMarker(id, def, item);
32804
+ }
32805
+ var props = item.f.properties || {};
32806
+ var content = o.render(props, item.f);
32807
+ while (el.firstChild) { el.removeChild(el.firstChild); }
32808
+ if (isElement(content)) { el.appendChild(content); } else if (content !== undefined && content !== null) { el.innerHTML = String(content); }
32809
+ el.className = 'smap-marker' + (o.className ? ' ' + o.className : '') + (o.onClick || o.popup || o.draggable || o.tooltip || o.riseOnHover ? ' smap-marker-interactive' : '');
32810
+ var opacity = plainValue(o.opacity, props, item.f, 1);
32811
+ el.style.opacity = opacity === 1 ? '' : String(opacity);
32812
+ item.z = +plainValue(o.zIndex, props, item.f, 0) || 0;
32813
+ item.sig = true;
32814
+ return el;
32815
+ };
32816
+
32817
+ // The anchor and offset of a layer's markers as a CSS transform tail.
32818
+ function anchorTransform(o) {
32819
+ var a = ANCHORS[o.anchor || 'center'], off = offsetOf(o.offset);
32820
+ return ' translate(' + a[0] + '%, ' + a[1] + '%)' + (off[0] || off[1] ? ' translate(' + off[0] + 'px, ' + off[1] + 'px)' : '');
32821
+ }
32822
+
32823
+ // Places every custom marker in view (and takes the ones that left the view out of the page).
32824
+ SMap.prototype._layoutMarkers = function () {
32825
+ var m = this.engine;
32826
+ if (!m || !this._overlay) { return; }
32827
+ var host = this._overlay;
32828
+ var w = host.clientWidth || (m.getContainer && m.getContainer().clientWidth) || 0;
32829
+ var h = host.clientHeight || (m.getContainer && m.getContainer().clientHeight) || 0;
32830
+ var zoom = m.getZoom ? m.getZoom() : 0;
32831
+ var rank = 0;
32832
+ for (var n = 0; n < this._order.length; n++) {
32833
+ var id = this._order[n], layer = this._layers[id];
32834
+ // A custom marker layer, or the HTML clusters of a point layer (cluster.html / cluster.ring).
32835
+ var def = layer.kind === 'custom' ? layer : layer.clusterSet;
32836
+ if (!def || !def.custom) { continue; }
32837
+ rank += 1;
32838
+ var o = def.o;
32839
+ var inRange = !layer.hidden && (o.minzoom === undefined || zoom >= o.minzoom) && (o.maxzoom === undefined || zoom < o.maxzoom);
32840
+ var tail = anchorTransform(o);
32841
+ var items = def.custom.items;
32842
+ for (var i = 0; i < items.length; i++) {
32843
+ var item = items[i];
32844
+ var at = item.dragAt || pointOf(item.f);
32845
+ var p = inRange && at ? m.project(at) : null;
32846
+ var visible = !!p && p.x >= -MARKER_MARGIN && p.y >= -MARKER_MARGIN && p.x <= w + MARKER_MARGIN && p.y <= h + MARKER_MARGIN;
32847
+ if (!visible) {
32848
+ if (item.shown && item.el && item.el.parentNode) { item.el.parentNode.removeChild(item.el); }
32849
+ item.shown = false;
32850
+ continue;
32851
+ }
32852
+ if (!item.el || !item.sig) { this._renderMarker(id, def, item); }
32853
+ var x = Math.round(p.x * 10) / 10, y = Math.round(p.y * 10) / 10;
32854
+ if (x !== item.x || y !== item.y) {
32855
+ item.el.style.transform = 'translate(' + x + 'px, ' + y + 'px)' + tail;
32856
+ item.x = x; item.y = y;
32857
+ }
32858
+ var z = rank * 100000 + (item.raised ? 99999 : Math.max(-99999, Math.min(99998, item.z)));
32859
+ if (item.zSet !== z) { item.el.style.zIndex = String(z); item.zSet = z; }
32860
+ if (!item.shown || item.el.parentNode !== host) { host.appendChild(item.el); item.shown = true; }
32861
+ }
32862
+ }
32863
+ };
32864
+
32865
+ // Click, popup, hover raise, tooltip and dragging of one custom marker.
32866
+ SMap.prototype._bindMarker = function (id, def, item) {
32867
+ var self = this, el = item.el;
32868
+ var o = function () { return def.o; };
32869
+ // The click a drag's release makes is no tap: stopped on the way down, before anything inside the marker (the
32870
+ // app's own buttons, a framework listening on its own element) sees it.
32871
+ el.addEventListener('click', function (e) {
32872
+ if (self._dragEndedAt && Date.now() - self._dragEndedAt < 300) { e.stopPropagation(); if (e.preventDefault) { e.preventDefault(); } }
32873
+ }, true);
32874
+ el.addEventListener('click', function (e) {
32875
+ if (self._dragEndedAt && Date.now() - self._dragEndedAt < 300) { e.stopPropagation(); return; }
32876
+ var lo = o();
32877
+ if (!lo.onClick && !lo.popup) { return; }
32878
+ e.stopPropagation();
32879
+ if (lo.onClick) { lo.onClick(item.f, { originalEvent: e, lngLat: pointOf(item.f) }); }
32880
+ if (lo.popup) { self._markerPopup(id, def, item); }
32881
+ });
32882
+ el.addEventListener('mouseenter', function (e) {
32883
+ var lo = o();
32884
+ if (lo.riseOnHover) { item.raised = true; self._layoutMarkers(); }
32885
+ if (lo.tooltip) { self._showTooltip(id, def, item.f, { element: el }); }
32886
+ });
32887
+ el.addEventListener('mouseleave', function () {
32888
+ if (item.raised) { item.raised = false; self._layoutMarkers(); }
32889
+ if (self._tooltipFor && self._tooltipFor.f === item.f) { self._hideTooltip(); }
32890
+ });
32891
+ var start = function (e) {
32892
+ var lo = o();
32893
+ if (!plainValue(lo.draggable, item.f.properties || {}, item.f, false)) { return; }
32894
+ if (e.button !== undefined && e.button !== 0) { return; }
32895
+ self._startMarkerDrag(id, item, e);
32896
+ };
32897
+ if (typeof el.addEventListener === 'function') {
32898
+ el.addEventListener(typeof window !== 'undefined' && window.PointerEvent ? 'pointerdown' : 'mousedown', start);
32899
+ }
32900
+ };
32901
+
32902
+ SMap.prototype._markerPopup = function (id, def, item) {
32903
+ var o = def.o, fn = def.popupFn || o.popup, content;
32904
+ try { content = fn(item.f.properties || {}, item.f); } catch (error) { this._reportError(error); return; }
32905
+ var options = Object.assign({}, o.popupOptions || {});
32906
+ if (options.offset === undefined && this._popupDefaults.offset === undefined && item.el) {
32907
+ // Above the element as it is drawn: from its anchor to its top edge.
32908
+ var hgt = item.el.offsetHeight || 0, a = ANCHORS[o.anchor || 'center'];
32909
+ options.offset = Math.round(hgt * (-a[1] / 100) - offsetOf(o.offset)[1] + 4);
32910
+ }
32911
+ if (options.anchor === undefined && this._popupDefaults.anchor === undefined) { options.anchor = 'bottom'; }
32912
+ this.openPopup(pointOf(item.f), content, options);
32913
+ };
32914
+
32915
+ // Dragging a custom marker: it follows the pointer from the first move of DRAG_THRESHOLD pixels; the map does not
32916
+ // pan meanwhile. Its layer's data then holds the new position (a copy: the caller's objects are not changed).
32917
+ SMap.prototype._startMarkerDrag = function (id, item, e) {
32918
+ var self = this, m = this.engine, el = item.el;
32919
+ var doc = el.ownerDocument, win = doc.defaultView || {};
32920
+ var box = m.getContainer().getBoundingClientRect();
32921
+ var p0 = m.project(pointOf(item.f));
32922
+ var grab = { x: e.clientX - box.left - p0.x, y: e.clientY - box.top - p0.y };
32923
+ var sx = e.clientX, sy = e.clientY, dragging = false;
32924
+ // The map must not pan under a marker that can be dragged: off from the press, back on at the release.
32925
+ var panWasOn = !!(m.dragPan && m.dragPan.isEnabled && m.dragPan.isEnabled());
32926
+ if (panWasOn) { m.dragPan.disable(); }
32927
+ var lngLatAt = function (ev) {
32928
+ var r = m.getContainer().getBoundingClientRect();
32929
+ var pt = { x: ev.clientX - r.left - grab.x, y: ev.clientY - r.top - grab.y };
32930
+ var ll = m.unproject([pt.x, pt.y]);
32931
+ return { lngLat: [ll.lng, ll.lat], point: pt };
32932
+ };
32933
+ var evt = function (ev, at) { return { lngLat: at.lngLat, point: at.point, originalEvent: ev }; };
32934
+ var move = function (ev) {
32935
+ if (!dragging) {
32936
+ if (Math.abs(ev.clientX - sx) < DRAG_THRESHOLD && Math.abs(ev.clientY - sy) < DRAG_THRESHOLD) { return; }
32937
+ dragging = true;
32938
+ el.classList.add('smap-marker-dragging');
32939
+ item.raised = true;
32940
+ self._hideTooltip();
32941
+ var o0 = self._layers[id].o;
32942
+ if (o0.onDragStart) { o0.onDragStart(item.f, evt(ev, lngLatAt(ev))); }
32943
+ }
32944
+ if (ev.preventDefault) { ev.preventDefault(); }
32945
+ var at = lngLatAt(ev);
32946
+ item.dragAt = at.lngLat;
32947
+ self._layoutMarkers();
32948
+ var o1 = self._layers[id] && self._layers[id].o;
32949
+ if (o1 && o1.onDrag) { o1.onDrag(item.f, evt(ev, at)); }
32950
+ };
32951
+ var up = function (ev) {
32952
+ doc.removeEventListener(upType, up);
32953
+ doc.removeEventListener(moveType, move);
32954
+ if (panWasOn) { m.dragPan.enable(); }
32955
+ if (!dragging) { return; }
32956
+ var at = lngLatAt(ev);
32957
+ item.dragAt = null;
32958
+ item.raised = false;
32959
+ el.classList.remove('smap-marker-dragging');
32960
+ self._dragEndedAt = Date.now();
32961
+ var def = self._layers[id];
32962
+ if (!def) { return; }
32963
+ def.data = movedCollection(def.data, item.index, at.lngLat);
32964
+ item.f = def.data.features[item.index];
32965
+ self._layoutMarkers();
32966
+ if (def.o.onDragEnd) { def.o.onDragEnd(item.f, evt(ev, at)); }
32967
+ };
32968
+ var pointer = !!win.PointerEvent && e.type === 'pointerdown';
32969
+ var moveType = pointer ? 'pointermove' : 'mousemove';
32970
+ var upType = pointer ? 'pointerup' : 'mouseup';
32971
+ doc.addEventListener(moveType, move);
32972
+ doc.addEventListener(upType, up);
32973
+ if (e.stopPropagation) { e.stopPropagation(); }
32974
+ };
32975
+
32976
+ // Dragging a drawn point (addPoints with draggable): the point is taken out of its layer and drawn in a copy of the
32977
+ // layer's own look that follows the pointer, then put back at the new position. Two data updates per drag, whatever
32978
+ // the size of the layer.
32979
+ SMap.prototype._dragPoints = function (id, def, main) {
32980
+ var self = this, m = this.engine;
32981
+ var begin = function (e) {
32982
+ var f = e.features && e.features[0];
32983
+ if (!f || def.hidden) { return; }
32984
+ var index = self._featureIndex(def, f);
32985
+ if (index < 0) { return; }
32986
+ var original = def.data.features[index];
32987
+ if (!plainValue(def.o.draggable, original.properties || {}, original, false)) { return; }
32988
+ if (e.originalEvent && e.originalEvent.button !== undefined && e.originalEvent.button !== 0) { return; }
32989
+ e.preventDefault();
32990
+ var start = e.point, dragging = false, ghost = null;
32991
+ var at = function (ev) { return { lngLat: [ev.lngLat.lng, ev.lngLat.lat], point: { x: ev.point.x, y: ev.point.y }, originalEvent: ev.originalEvent }; };
32992
+ var move = function (ev) {
32993
+ if (!dragging) {
32994
+ if (Math.abs(ev.point.x - start.x) < DRAG_THRESHOLD && Math.abs(ev.point.y - start.y) < DRAG_THRESHOLD) { return; }
32995
+ dragging = true;
32996
+ if (m.dragPan && m.dragPan.disable) { m.dragPan.disable(); }
32997
+ ghost = self._dragGhost(id, def);
32998
+ var without = def.data.features.slice();
32999
+ without.splice(index, 1);
33000
+ var src = m.getSource('smap-' + id);
33001
+ if (src) { src.setData({ type: 'FeatureCollection', features: without }); }
33002
+ if (def.hovered) { self._setHover(id, def, null); }
33003
+ self._hideTooltip();
33004
+ if (def.o.onDragStart) { def.o.onDragStart(original, at(ev)); }
33005
+ }
33006
+ var a = at(ev);
33007
+ if (ghost) { ghost.setData({ type: 'FeatureCollection', features: [Object.assign({}, original, { geometry: { type: 'Point', coordinates: a.lngLat } })] }); }
33008
+ if (def.o.onDrag) { def.o.onDrag(original, a); }
33009
+ };
33010
+ var end = function (ev) {
33011
+ m.off('mousemove', move); m.off('touchmove', move);
33012
+ m.off('mouseup', end); m.off('touchend', end);
33013
+ if (!dragging) { return; }
33014
+ if (m.dragPan && m.dragPan.enable) { m.dragPan.enable(); }
33015
+ self._dropGhost(id);
33016
+ self._dragEndedAt = Date.now();
33017
+ var a = at(ev);
33018
+ def.data = movedCollection(def.data, index, a.lngLat);
33019
+ var src = m.getSource('smap-' + id);
33020
+ if (src) { src.setData(def.data); }
33021
+ if (def.o.onDragEnd) { def.o.onDragEnd(def.data.features[index], a); }
33022
+ };
33023
+ m.on('mousemove', move); m.on('touchmove', move);
33024
+ m.on('mouseup', end); m.on('touchend', end);
33025
+ };
33026
+ this._listen(id, 'mousedown', main, begin);
33027
+ this._listen(id, 'touchstart', main, begin);
33028
+ };
33029
+
33030
+ // The index in a layer's data of a feature the engine answered (by idProperty, else by the generated id).
33031
+ SMap.prototype._featureIndex = function (def, f) {
33032
+ var feats = def.data.features, idp = def.o.idProperty;
33033
+ if (idp) {
33034
+ var want = f.properties ? f.properties[idp] : undefined;
33035
+ for (var i = 0; i < feats.length; i++) { if (feats[i].properties && feats[i].properties[idp] === want) { return i; } }
33036
+ return -1;
33037
+ }
33038
+ return typeof f.id === 'number' && f.id >= 0 && f.id < feats.length ? f.id : -1;
33039
+ };
33040
+
33041
+ // A copy of a layer's engine layers drawing from a one-feature source on top of the map: the point being dragged.
33042
+ SMap.prototype._dragGhost = function (id, def) {
33043
+ var m = this.engine, src = 'smap-' + id, ghostSrc = src + '-drag';
33044
+ this._dropGhost(id);
33045
+ m.addSource(ghostSrc, { type: 'geojson', data: { type: 'FeatureCollection', features: [] } });
33046
+ var st = m.getStyle ? m.getStyle() : null;
33047
+ var ids = [];
33048
+ (st && st.layers ? st.layers : []).forEach(function (l) {
33049
+ if (l.source !== src || def.engineLayers.indexOf(l.id) < 0 || /-(clusters|count)$/.test(l.id)) { return; }
33050
+ var copy = JSON.parse(JSON.stringify(l));
33051
+ copy.id = l.id + '-drag';
33052
+ copy.source = ghostSrc;
33053
+ delete copy.minzoom; delete copy.maxzoom;
33054
+ copy.layout = Object.assign({}, copy.layout || {}, { visibility: 'visible' });
33055
+ m.addLayer(copy);
33056
+ ids.push(copy.id);
33057
+ });
33058
+ this._ghost = { id: id, source: ghostSrc, layers: ids };
33059
+ return m.getSource(ghostSrc);
33060
+ };
33061
+
33062
+ SMap.prototype._dropGhost = function (id) {
33063
+ var g = this._ghost, m = this.engine;
33064
+ if (!g || (id && g.id !== id)) { return; }
33065
+ g.layers.forEach(function (l) { if (m.getLayer(l)) { m.removeLayer(l); } });
33066
+ if (m.getSource(g.source)) { m.removeSource(g.source); }
33067
+ this._ghost = null;
33068
+ };
33069
+
33070
+ // ---- tooltips (G5)
33071
+
33072
+ /**
33073
+ * The map's one tooltip: shown while the pointer is over a feature of a layer with `tooltip`, beside the point (or
33074
+ * the custom marker), or at the pointer on lines and areas. `tooltipOptions`: direction ('top' default, 'bottom',
33075
+ * 'left', 'right'), offset ([x, y] pixels), className.
33076
+ */
33077
+ SMap.prototype._showTooltip = function (id, def, f, at) {
33078
+ var o = def.o, content;
33079
+ var fn = typeof o.tooltip === 'string' ? (def.tooltipFn = def.tooltipFn || popupTemplate(o.tooltip)) : o.tooltip;
33080
+ try { content = fn(f.properties || {}, f); } catch (error) { this._reportError(error); return; }
33081
+ if (content === undefined || content === null || content === '') { this._hideTooltip(); return; }
33082
+ var m = this.engine, overlay = this._markerOverlay(), doc = overlay.ownerDocument;
33083
+ var tip = this._tooltip;
33084
+ if (!tip || tip.parentNode !== overlay) {
33085
+ tip = this._tooltip = doc.createElement('div');
33086
+ overlay.appendChild(tip);
33087
+ }
33088
+ var to = o.tooltipOptions || {};
33089
+ var dir = ['top', 'bottom', 'left', 'right'].indexOf(to.direction) >= 0 ? to.direction : 'top';
33090
+ tip.className = 'smap-tooltip smap-tooltip-' + dir + (to.className ? ' ' + to.className : '');
33091
+ while (tip.firstChild) { tip.removeChild(tip.firstChild); }
33092
+ if (isElement(content)) { tip.appendChild(content); } else { tip.innerHTML = String(content); }
33093
+ var x, y, gap = 6;
33094
+ if (at.element) {
33095
+ var hb = overlay.getBoundingClientRect(), eb = at.element.getBoundingClientRect();
33096
+ x = eb.left - hb.left + eb.width / 2; y = eb.top - hb.top + eb.height / 2;
33097
+ if (dir === 'top') { y = eb.top - hb.top; } else if (dir === 'bottom') { y = eb.bottom - hb.top; }
33098
+ else if (dir === 'left') { x = eb.left - hb.left; } else { x = eb.right - hb.left; }
33099
+ } else {
33100
+ var p = at.point || m.project(at.lngLat);
33101
+ x = p.x; y = p.y;
33102
+ gap = at.gap !== undefined ? at.gap : 10;
33103
+ }
33104
+ var off = offsetOf(to.offset);
33105
+ var shift = { top: [-50, -100, 0, -gap], bottom: [-50, 0, 0, gap], left: [-100, -50, -gap, 0], right: [0, -50, gap, 0] }[dir];
33106
+ 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] + '%)';
33107
+ this._tooltipFor = { id: id, f: f };
33108
+ };
33109
+
33110
+ SMap.prototype._hideTooltip = function () {
33111
+ if (this._tooltip && this._tooltip.parentNode) { this._tooltip.parentNode.removeChild(this._tooltip); }
33112
+ this._tooltipFor = null;
33113
+ };
33114
+
33115
+ // Tooltips of a drawn layer: points show theirs beside the point, lines and areas at the pointer.
33116
+ SMap.prototype._tooltips = function (id, def, main) {
33117
+ var self = this, m = this.engine;
33118
+ this._listen(id, 'mousemove', main, function (e) {
33119
+ var f = e.features && e.features[0];
33120
+ if (!f || def.hidden) { return; }
33121
+ if (def.kind === 'points' && pointOf(f) && !(f.properties && f.properties.point_count)) {
33122
+ var mk = def.o.marker, k = mk ? scaleAt(mk.scale, m.getZoom()) : 1;
33123
+ var size = mk ? (mk.size || 32) * k : (def.o.radius || 6) * 2;
33124
+ var gap = mk && (mk.shape === undefined || mk.shape === 'pin') ? Math.round(size * 1.25) : Math.round(size / 2 + 4);
33125
+ self._showTooltip(id, def, f, { lngLat: pointOf(f), gap: gap });
33126
+ } else {
33127
+ self._showTooltip(id, def, f, { point: e.point, gap: 12 });
33128
+ }
33129
+ });
33130
+ this._listen(id, 'mouseleave', main, function () { if (self._tooltipFor && self._tooltipFor.id === id) { self._hideTooltip(); } });
33131
+ };
33132
+
33133
+ // ---- clusters drawn as HTML (G6)
33134
+
33135
+ // Colours of a ring: each value's share of the points, largest first; up to six slices, the rest in the last.
33136
+ function ringBackground(counts, fallback) {
33137
+ var keys = Object.keys(counts).sort(function (a, b) { return counts[b] - counts[a]; });
33138
+ var total = keys.reduce(function (t, k) { return t + counts[k]; }, 0);
33139
+ if (!total) { return fallback; }
33140
+ if (keys.length === 1) { return keys[0]; }
33141
+ var shown = keys.slice(0, 6), at = 0;
33142
+ return 'conic-gradient(' + shown.map(function (c, i) {
33143
+ var from = at;
33144
+ at = i === shown.length - 1 ? 100 : Math.min(100, at + Math.round(counts[c] / total * 100));
33145
+ return c + ' ' + from + '% ' + at + '%';
33146
+ }).join(', ') + ')';
33147
+ }
33148
+
33149
+ // The cluster as the caller's html() sees it.
33150
+ SMap.prototype._clusterInfo = function (src, f) {
33151
+ var m = this.engine, p = f.properties || {};
33152
+ return {
33153
+ id: p.cluster_id, count: p.point_count, properties: p, lngLat: pointOf(f),
33154
+ leaves: function (limit) {
33155
+ var source = m.getSource(src);
33156
+ return Promise.resolve(source.getClusterLeaves(p.cluster_id, limit === undefined ? Infinity : limit, 0));
33157
+ },
33158
+ };
33159
+ };
33160
+
33161
+ // HTML clusters of a point layer: the clusters the engine made are read after each change of view or data and laid
33162
+ // out as custom markers (kept by cluster id, so an unchanged cluster keeps its element).
33163
+ SMap.prototype._htmlClusters = function (id, def, src) {
33164
+ var self = this, m = this.engine, co = def.o.cluster;
33165
+ var ring = co.ring ? (typeof co.ring === 'string' ? { property: co.ring } : co.ring) : null;
33166
+ var render = function (props, f) {
33167
+ var info = self._clusterInfo(src, f);
33168
+ if (co.html) { return co.html(info); }
33169
+ var size = info.count >= 100 ? 44 : (info.count >= 10 ? 38 : 32);
33170
+ var doc = self._markerOverlay().ownerDocument;
33171
+ var el = doc.createElement('div');
33172
+ el.className = 'smap-cluster';
33173
+ el.style.width = el.style.height = size + 'px';
33174
+ el.style.background = ring.color || def.o.clusterColor || def.o.color || '#4f46e5';
33175
+ var b = doc.createElement('b');
33176
+ b.textContent = String(info.count);
33177
+ el.appendChild(b);
33178
+ // The ring: the share of each value among the cluster's points (read from at most ring.limit of them).
33179
+ info.leaves(ring.limit || 500).then(function (leaves) {
33180
+ var counts = {};
33181
+ (leaves || []).forEach(function (leaf) {
33182
+ var c = leaf.properties ? leaf.properties[ring.property] : undefined;
33183
+ if (typeof c === 'string' && c) { counts[c] = (counts[c] || 0) + 1; }
33184
+ });
33185
+ el.style.background = ringBackground(counts, el.style.background);
33186
+ }, function () {});
33187
+ return el;
33188
+ };
33189
+ def.clusterSet = {
33190
+ o: {
33191
+ render: render, anchor: 'center', className: co.className, riseOnHover: true,
33192
+ // A click zooms in to where the cluster splits (cluster.zoomOnClick: false turns it off).
33193
+ onClick: co.zoomOnClick === false ? co.onClick : function (f, e) {
33194
+ if (co.onClick) { co.onClick(f, e); }
33195
+ var source = m.getSource(src);
33196
+ Promise.resolve(source.getClusterExpansionZoom(f.properties.cluster_id)).then(function (zoom) {
33197
+ m.easeTo({ center: pointOf(f), zoom: zoom });
33198
+ }, function () {});
33199
+ },
33200
+ tooltip: co.tooltip ? function (p, f) { return co.tooltip(self._clusterInfo(src, f)); } : undefined,
33201
+ },
33202
+ data: { type: 'FeatureCollection', features: [] },
33203
+ custom: null,
33204
+ };
33205
+ var refresh = function () {
33206
+ var set = def.clusterSet;
33207
+ if (!set || !m.getSource(src)) { return; }
33208
+ var seen = {}, features = [];
33209
+ (m.querySourceFeatures(src, { filter: ['has', 'point_count'] }) || []).forEach(function (f) {
33210
+ var cid = f.properties && f.properties.cluster_id;
33211
+ if (cid === undefined || seen[cid]) { return; }
33212
+ seen[cid] = true;
33213
+ features.push({ type: 'Feature', id: 'c' + cid, properties: f.properties, geometry: { type: 'Point', coordinates: pointOf(f) } });
33214
+ });
33215
+ set.data = { type: 'FeatureCollection', features: features };
33216
+ self._markerOverlay();
33217
+ self._customData(id + ':clusters', set);
33218
+ };
33219
+ this._listen(id, 'moveend', null, refresh);
33220
+ this._listen(id, 'sourcedata', null, function (e) { if (e && e.sourceId === src && e.isSourceLoaded) { refresh(); } });
33221
+ refresh();
33222
+ };
33223
+
30962
33224
  // ------------------------------------------------------------------ map tools (M49-M57)
30963
33225
 
30964
33226
  var TOOL_ID = /^[A-Za-z0-9._-]{1,64}$/;
@@ -30973,6 +33235,8 @@ function smapCreateSdk(engine, interop, plan) {
30973
33235
  zoom: { control: 'NavigationControl', label: 'Zoom', position: 'top-left', options: { showCompass: false } },
30974
33236
  compass: { control: 'NavigationControl', label: 'Compass', position: 'top-left', options: { showZoom: false } },
30975
33237
  locate: { control: 'GeolocateControl', label: 'Locate', position: 'top-left' },
33238
+ // Made by the SDK itself: the base map and overlay switcher (G8).
33239
+ layers: { sdk: 'layers', label: 'Layers', position: 'top-right' },
30976
33240
  };
30977
33241
  var TOOLS_ICON = '<svg viewBox="0 0 24 24" width="18" height="18" aria-hidden="true" focusable="false" fill="none" ' +
30978
33242
  'stroke="currentColor" stroke-width="2" stroke-linecap="round"><path d="M4 7h10M18 7h2M4 17h2M10 17h10"/>' +
@@ -31043,7 +33307,7 @@ function smapCreateSdk(engine, interop, plan) {
31043
33307
  }
31044
33308
  if (typeof target === 'string') {
31045
33309
  if (!kind) { throw new Error('sMap: unknown tool kind "' + target + '"'); }
31046
- if (!engine[kind.control]) { throw new Error('sMap: the rendering engine has no ' + kind.control); }
33310
+ if (!kind.sdk && !this._lib[kind.control]) { throw new Error('sMap: the rendering engine has no ' + kind.control); }
31047
33311
  } else if (!isElement(target) && !(target && typeof target.onAdd === 'function')) {
31048
33312
  throw new Error('sMap: a tool is an element, an engine control or a tool kind');
31049
33313
  }
@@ -31052,7 +33316,8 @@ function smapCreateSdk(engine, interop, plan) {
31052
33316
  if (position === 'none' && !isElement(target)) { throw new Error('sMap: only an element may stay out of the map\'s corners'); }
31053
33317
  if (this._toolIndex(id) >= 0) { this.removeTool(id); }
31054
33318
  var tool = { id: id, label: String(o.label || (kind ? kind.label : id)), position: position, el: null, control: null };
31055
- if (kind) { tool.control = toolControl(tool, new engine[kind.control](o.options || kind.options)); }
33319
+ if (kind && kind.sdk === 'layers') { tool.control = toolControl(tool, layersControl(this, o.options || {})); }
33320
+ else if (kind) { tool.control = toolControl(tool, new this._lib[kind.control](o.options || kind.options)); }
31056
33321
  else if (!isElement(target)) { tool.control = toolControl(tool, target); }
31057
33322
  else if (position !== 'none') { tool.control = elementControl(tool, target); }
31058
33323
  else { tool.el = target; }
@@ -31305,6 +33570,1119 @@ function smapCreateSdk(engine, interop, plan) {
31305
33570
  return control;
31306
33571
  }
31307
33572
 
33573
+ // ------------------------------------------------------------------ heat maps (G7), terrain (G11), synced maps (G13), drawn tiles (G14)
33574
+
33575
+ /**
33576
+ * A heat map of points: weight (a number, or per feature: { property } or an expression; default 1), radius
33577
+ * (pixels, default 20, or an expression of the zoom), intensity (default 1), opacity (default 0.8), colors (from low
33578
+ * to high, or [[density 0–1, colour], …]), minzoom, maxzoom, slot, before, zIndex.
33579
+ */
33580
+ SMap.prototype.addHeatmap = function (id, data, o) {
33581
+ this._define(id, { kind: 'heatmap', data: toFeatureCollection(data), o: o || {} });
33582
+ return this;
33583
+ };
33584
+
33585
+ var TERRAIN_SOURCE = 'smap-terrain';
33586
+ var HILLSHADE_LAYER = 'smap-hillshade';
33587
+
33588
+ /**
33589
+ * Relief: the map drawn over elevation tiles (seen when the map is tilted), with optional hillshading.
33590
+ * @param {Object|null} terrain { tiles: [url with {z}/{x}/{y}], encoding: 'terrarium' | 'mapbox' (default terrarium),
33591
+ * tileSize (256), maxzoom (15), attribution, exaggeration (1), hillshade (true, or { exaggeration, shadow,
33592
+ * highlight }) }; null takes it off
33593
+ */
33594
+ SMap.prototype.setTerrain = function (terrain) {
33595
+ if (terrain && (!Array.isArray(terrain.tiles) || !terrain.tiles.length)) { throw new Error('sMap: terrain needs tiles'); }
33596
+ this._terrain = terrain ? Object.assign({}, terrain) : null;
33597
+ if (this.engine && this._styleReady) { this._applyTerrain(); }
33598
+ return this;
33599
+ };
33600
+
33601
+ SMap.prototype._applyTerrain = function () {
33602
+ var m = this.engine, t = this._terrain;
33603
+ if (m.setTerrain) { m.setTerrain(null); }
33604
+ if (m.getLayer(HILLSHADE_LAYER)) { m.removeLayer(HILLSHADE_LAYER); }
33605
+ if (m.getSource(TERRAIN_SOURCE)) { m.removeSource(TERRAIN_SOURCE); }
33606
+ if (m.getSource(TERRAIN_SOURCE + '-shade')) { m.removeSource(TERRAIN_SOURCE + '-shade'); }
33607
+ if (!t) { return; }
33608
+ var source = { type: 'raster-dem', tiles: t.tiles.slice(), tileSize: t.tileSize || 256, encoding: t.encoding || 'terrarium', maxzoom: t.maxzoom || 15 };
33609
+ if (t.attribution) { source.attribution = t.attribution; }
33610
+ m.addSource(TERRAIN_SOURCE, source);
33611
+ if (t.hillshade !== false) {
33612
+ var hs = t.hillshade && typeof t.hillshade === 'object' ? t.hillshade : {};
33613
+ var paint = { 'hillshade-exaggeration': hs.exaggeration !== undefined ? hs.exaggeration : 0.35 };
33614
+ if (hs.shadow) { paint['hillshade-shadow-color'] = hs.shadow; }
33615
+ if (hs.highlight) { paint['hillshade-highlight-color'] = hs.highlight; }
33616
+ // Over land and water, under the roads; from a source of its own (the engine draws the relief and the shading
33617
+ // better from two sources than from one).
33618
+ m.addSource(TERRAIN_SOURCE + '-shade', Object.assign({}, source, { tiles: source.tiles.slice() }));
33619
+ m.addLayer({ id: HILLSHADE_LAYER, type: 'hillshade', source: TERRAIN_SOURCE + '-shade', paint: paint }, this.slots().roads || undefined);
33620
+ }
33621
+ if (m.setTerrain) { m.setTerrain({ source: TERRAIN_SOURCE, exaggeration: t.exaggeration || 1 }); }
33622
+ };
33623
+
33624
+ /**
33625
+ * Keeps another sMap map on this map's view, both ways (a picture in picture, a before / after pair). `offsetZoom`
33626
+ * is added to this map's zoom on the other (e.g. -3 for an overview). Returns a function that ends it.
33627
+ */
33628
+ SMap.prototype.syncWith = function (other, options) {
33629
+ var self = this, offset = (options && options.offsetZoom) || 0, busy = false;
33630
+ if (!other || !(other instanceof SMap)) { throw new Error('sMap: syncWith takes another sMap map'); }
33631
+ var copy = function (from, to, dz) {
33632
+ return function () {
33633
+ if (busy || !from.engine || !to.engine) { return; }
33634
+ busy = true;
33635
+ try {
33636
+ var c = from.engine.getCenter();
33637
+ to.engine.jumpTo({ center: [c.lng, c.lat], zoom: from.engine.getZoom() + dz, bearing: from.engine.getBearing(), pitch: from.engine.getPitch() });
33638
+ } finally { busy = false; }
33639
+ };
33640
+ };
33641
+ var a = copy(this, other, offset), b = copy(other, this, -offset);
33642
+ Promise.all([this.ready, other.ready]).then(function () {
33643
+ if (!a) { return; }
33644
+ self.engine.on('move', a);
33645
+ other.engine.on('move', b);
33646
+ a();
33647
+ });
33648
+ return function () {
33649
+ if (self.engine) { self.engine.off('move', a); }
33650
+ if (other.engine) { other.engine.off('move', b); }
33651
+ a = null;
33652
+ };
33653
+ };
33654
+
33655
+ // Tiles drawn by the page: one protocol for every map, each layer its own key.
33656
+ var canvasTiles = {};
33657
+ var canvasSeq = 0;
33658
+ var canvasRegistered = false;
33659
+ function registerCanvasProtocol(doc) {
33660
+ if (canvasRegistered) { return; }
33661
+ canvasRegistered = true;
33662
+ var handler = function (params) {
33663
+ var m = /^smapcanvas:\/\/([^/]+)\/(\d+)\/(\d+)\/(\d+)/.exec(params.url);
33664
+ var entry = m && canvasTiles[m[1]];
33665
+ if (!entry) { return Promise.reject(new Error('sMap: no drawn tiles for ' + params.url)); }
33666
+ var size = entry.tileSize * entry.ratio;
33667
+ var canvas = entry.doc.createElement('canvas');
33668
+ canvas.width = size; canvas.height = size;
33669
+ var ctx = canvas.getContext('2d');
33670
+ ctx.scale(entry.ratio, entry.ratio);
33671
+ return Promise.resolve(entry.draw(ctx, +m[2], +m[3], +m[4], { size: entry.tileSize, canvas: canvas })).then(function () {
33672
+ return new Promise(function (resolve, reject) {
33673
+ canvas.toBlob(function (blob) {
33674
+ if (!blob) { reject(new Error('sMap: a drawn tile could not be encoded')); return; }
33675
+ blob.arrayBuffer().then(function (data) { resolve({ data: data }); }, reject);
33676
+ }, 'image/png');
33677
+ });
33678
+ });
33679
+ };
33680
+ if (engine && engine.addProtocol) { engine.addProtocol('smapcanvas', handler); }
33681
+ if (canvasLib) { canvasLib.addProtocol('smapcanvas', handler); }
33682
+ }
33683
+
33684
+ /**
33685
+ * Raster tiles drawn by the page: draw(ctx, z, x, y, { size, canvas }) paints one tile (a 2D context already scaled
33686
+ * to `size` × `size` CSS pixels; may return a promise). Options as addRasterLayer (tileSize 256, minzoom, maxzoom,
33687
+ * opacity, attribution, slot, before, zIndex).
33688
+ */
33689
+ SMap.prototype.addCanvasTiles = function (id, draw, o) {
33690
+ if (typeof draw !== 'function') { throw new Error('sMap: addCanvasTiles needs draw(ctx, z, x, y)'); }
33691
+ o = o || {};
33692
+ var doc = (this.engine && this.engine.getContainer().ownerDocument) || (typeof document !== 'undefined' ? document : null);
33693
+ if (!doc) { throw new Error('sMap: addCanvasTiles needs a page'); }
33694
+ registerCanvasProtocol(doc);
33695
+ var key = 'c' + (++canvasSeq);
33696
+ var win = doc.defaultView || {};
33697
+ canvasTiles[key] = { draw: draw, tileSize: o.tileSize || 256, ratio: Math.min(2, Math.max(1, Math.ceil(win.devicePixelRatio || 1))), doc: doc };
33698
+ var source = { type: 'raster', tiles: ['smapcanvas://' + key + '/{z}/{x}/{y}'], tileSize: o.tileSize || 256 };
33699
+ copyKeys(o, source, ['attribution', 'minzoom', 'maxzoom', 'bounds']);
33700
+ return this._addRaster(id, source, o);
33701
+ };
33702
+
33703
+ // ------------------------------------------------------------------ drawing and editing shapes (G3), area selection (G4)
33704
+
33705
+ var DRAW_TEXT = {
33706
+ polygon: 'Polygon', rectangle: 'Rectangle', circle: 'Circle', line: 'Line', point: 'Point', hole: 'Hole',
33707
+ delete: 'Delete', undo: 'Undo', redo: 'Redo', finish: 'Finish', cancel: 'Cancel',
33708
+ };
33709
+ var DRAW_MODES = ['polygon', 'rectangle', 'circle', 'line', 'point'];
33710
+ var SNAP_PX = 10;
33711
+ var drawSeq = 0;
33712
+
33713
+ function closeRing(ring) {
33714
+ var r = ring.slice();
33715
+ if (r.length && (r[0][0] !== r[r.length - 1][0] || r[0][1] !== r[r.length - 1][1])) { r.push(r[0].slice()); }
33716
+ return r;
33717
+ }
33718
+ 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(); }
33719
+
33720
+ // A circle of `radius` metres as a ring of 64 points.
33721
+ function circleRing(center, radius) {
33722
+ // The same Earth radius as sMap.geo.distance, so the radius handle measures what was drawn.
33723
+ var ring = [], R = 6371008.8, lat = center[1] * Math.PI / 180;
33724
+ for (var i = 0; i <= 64; i++) {
33725
+ var a = (i % 64) / 64 * 2 * Math.PI;
33726
+ 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]);
33727
+ }
33728
+ return ring;
33729
+ }
33730
+
33731
+ // The editable rings of a geometry: [{ path: [polygon, ring] or [ring], coords (open), closed }].
33732
+ function ringsOf(g) {
33733
+ if (!g) { return []; }
33734
+ if (g.type === 'LineString') { return [{ path: [], coords: g.coordinates, closed: false }]; }
33735
+ if (g.type === 'Polygon') { return g.coordinates.map(function (r, i) { return { path: [i], coords: openRing(r), closed: true }; }); }
33736
+ if (g.type === 'MultiPolygon') {
33737
+ var out = [];
33738
+ g.coordinates.forEach(function (poly, p) { poly.forEach(function (r, i) { out.push({ path: [p, i], coords: openRing(r), closed: true }); }); });
33739
+ return out;
33740
+ }
33741
+ return [];
33742
+ }
33743
+
33744
+ function setRing(g, path, coords) {
33745
+ if (g.type === 'LineString') { g.coordinates = coords; return; }
33746
+ if (g.type === 'Polygon') { g.coordinates[path[0]] = closeRing(coords); return; }
33747
+ if (g.type === 'MultiPolygon') { g.coordinates[path[0]][path[1]] = closeRing(coords); }
33748
+ }
33749
+
33750
+ function moveGeometry(g, dx, dy) {
33751
+ (function walk(c) { if (typeof c[0] === 'number') { c[0] += dx; c[1] += dy; } else { c.forEach(walk); } })(g.coordinates);
33752
+ }
33753
+
33754
+ /**
33755
+ * A drawing and editing tool on this map. Shapes are kept by the tool as GeoJSON features (each with an id) and drawn
33756
+ * in its own layers; your page reads them with getAll() or from the events.
33757
+ * @param {Object} [o]
33758
+ * features (GeoJSON to start from), modes (the shapes offered, default all: polygon, rectangle, circle, line, point),
33759
+ * snap (true: a new or moved vertex within 10 px of another shape's vertex takes its place; default true),
33760
+ * toolbar (false, or a corner; default 'top-left'), labels (the toolbar's texts), color (default '#2563eb'),
33761
+ * onChange({ type: 'created' | 'edited' | 'deleted', feature, features }) after every change
33762
+ */
33763
+ SMap.prototype.drawTool = function (o) {
33764
+ return new DrawTool(this, o || {});
33765
+ };
33766
+
33767
+ function DrawTool(map, o) {
33768
+ this.map = map;
33769
+ this.o = o;
33770
+ this.id = 'smap-draw-' + (++drawSeq);
33771
+ this.color = o.color || '#2563eb';
33772
+ this.modes = (o.modes || DRAW_MODES).filter(function (k) { return DRAW_MODES.indexOf(k) >= 0; });
33773
+ this.snap = o.snap !== false;
33774
+ this.text = Object.assign({}, DRAW_TEXT, o.labels || {});
33775
+ this.features = [];
33776
+ this.seq = 0;
33777
+ this.selected = null; // feature id
33778
+ this.vertex = null; // { ring, index } of the selected vertex
33779
+ this.mode = null; // the shape being drawn
33780
+ this.sketch = null; // coordinates of the shape being drawn
33781
+ this.hover = null;
33782
+ this.undoStack = [];
33783
+ this.redoStack = [];
33784
+ this.handlers = {};
33785
+ var self = this;
33786
+ (o.features ? toFeatureCollection(o.features).features : []).forEach(function (f) { self.features.push(self._own(f)); });
33787
+ map.ready.then(function () { if (!self.destroyed) { self._mount(); } });
33788
+ }
33789
+
33790
+ DrawTool.prototype._own = function (f) {
33791
+ var copy = JSON.parse(JSON.stringify(f));
33792
+ if (copy.id === undefined || copy.id === null) { copy.id = 'f' + (++this.seq); }
33793
+ copy.properties = copy.properties || {};
33794
+ return copy;
33795
+ };
33796
+
33797
+ DrawTool.prototype.on = function (type, fn) { (this.handlers[type] = this.handlers[type] || []).push(fn); return this; };
33798
+ DrawTool.prototype.off = function (type, fn) { this.handlers[type] = (this.handlers[type] || []).filter(function (h) { return h !== fn; }); return this; };
33799
+ DrawTool.prototype._emit = function (type, feature) {
33800
+ var e = { type: type, feature: feature ? JSON.parse(JSON.stringify(feature)) : null, features: this.getAll() };
33801
+ (this.handlers[type] || []).slice().forEach(function (h) { h(e); });
33802
+ (this.handlers.change || []).slice().forEach(function (h) { h(e); });
33803
+ if (this.o.onChange) { this.o.onChange(e); }
33804
+ };
33805
+
33806
+ /** Every shape as a FeatureCollection (a copy). */
33807
+ DrawTool.prototype.getAll = function () { return JSON.parse(JSON.stringify({ type: 'FeatureCollection', features: this.features })); };
33808
+ DrawTool.prototype.get = function (id) { var f = this._find(id); return f ? JSON.parse(JSON.stringify(f)) : null; };
33809
+ /** Replaces every shape (not recorded for undo). */
33810
+ DrawTool.prototype.set = function (data) {
33811
+ var self = this;
33812
+ this.features = toFeatureCollection(data).features.map(function (f) { return self._own(f); });
33813
+ this.selected = null; this.vertex = null;
33814
+ this.undoStack = []; this.redoStack = [];
33815
+ this._render();
33816
+ return this;
33817
+ };
33818
+ 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; };
33819
+ DrawTool.prototype._record = function () {
33820
+ this.undoStack.push(JSON.stringify(this.features));
33821
+ if (this.undoStack.length > 100) { this.undoStack.shift(); }
33822
+ this.redoStack = [];
33823
+ };
33824
+ DrawTool.prototype.undo = function () {
33825
+ if (!this.undoStack.length) { return this; }
33826
+ this.redoStack.push(JSON.stringify(this.features));
33827
+ this.features = JSON.parse(this.undoStack.pop());
33828
+ if (this.selected && !this._find(this.selected)) { this.selected = null; }
33829
+ this.vertex = null;
33830
+ this._render();
33831
+ this._emit('edited', this.selected ? this._find(this.selected) : null);
33832
+ return this;
33833
+ };
33834
+ DrawTool.prototype.redo = function () {
33835
+ if (!this.redoStack.length) { return this; }
33836
+ this.undoStack.push(JSON.stringify(this.features));
33837
+ this.features = JSON.parse(this.redoStack.pop());
33838
+ if (this.selected && !this._find(this.selected)) { this.selected = null; }
33839
+ this.vertex = null;
33840
+ this._render();
33841
+ this._emit('edited', this.selected ? this._find(this.selected) : null);
33842
+ return this;
33843
+ };
33844
+
33845
+ /** Starts drawing a shape: 'polygon', 'rectangle', 'circle', 'line', 'point', or 'hole' (in the selected polygon). */
33846
+ DrawTool.prototype.start = function (mode) {
33847
+ if (mode === 'hole') {
33848
+ var f = this.selected && this._find(this.selected);
33849
+ if (!f || !f.geometry || f.geometry.type !== 'Polygon') { throw new Error('sMap: select a polygon to draw a hole in'); }
33850
+ } else if (DRAW_MODES.indexOf(mode) < 0) { throw new Error('sMap: unknown shape "' + mode + '"'); }
33851
+ this.mode = mode;
33852
+ this.sketch = [];
33853
+ this.vertex = null;
33854
+ if (mode !== 'hole') { this.selected = null; }
33855
+ this._render();
33856
+ this._renderToolbar();
33857
+ return this;
33858
+ };
33859
+
33860
+ /** Stops drawing without keeping the shape being drawn. */
33861
+ DrawTool.prototype.cancel = function () { this.mode = null; this.sketch = null; this._render(); this._renderToolbar(); return this; };
33862
+
33863
+ /** Selects a shape for editing (null to deselect). */
33864
+ DrawTool.prototype.select = function (id) { this.selected = id && this._find(id) ? id : null; this.vertex = null; this._render(); this._renderToolbar(); return this; };
33865
+ DrawTool.prototype.selection = function () { return this.selected; };
33866
+
33867
+ /** Deletes a shape (default: the selected one); with a vertex selected, deletes that vertex instead. */
33868
+ DrawTool.prototype.delete = function (id) {
33869
+ if (id === undefined && this.vertex && this.selected) { return this._deleteVertex(); }
33870
+ id = id === undefined ? this.selected : id;
33871
+ var f = this._find(id);
33872
+ if (!f) { return this; }
33873
+ this._record();
33874
+ this.features = this.features.filter(function (x) { return x !== f; });
33875
+ if (this.selected === id) { this.selected = null; this.vertex = null; }
33876
+ this._render();
33877
+ this._renderToolbar();
33878
+ this._emit('deleted', f);
33879
+ return this;
33880
+ };
33881
+
33882
+ DrawTool.prototype._deleteVertex = function () {
33883
+ var f = this._find(this.selected), v = this.vertex;
33884
+ var rings = ringsOf(f.geometry), r = rings[v.ring];
33885
+ if (!r || r.coords.length <= (r.closed ? 3 : 2)) { return this; }
33886
+ this._record();
33887
+ var coords = r.coords.slice();
33888
+ coords.splice(v.index, 1);
33889
+ setRing(f.geometry, r.path, coords);
33890
+ this.vertex = null;
33891
+ this._render();
33892
+ this._emit('edited', f);
33893
+ return this;
33894
+ };
33895
+
33896
+ DrawTool.prototype.destroy = function () {
33897
+ this.destroyed = true;
33898
+ var m = this.map.engine;
33899
+ if (!m) { return; }
33900
+ var self = this;
33901
+ (this.listeners || []).forEach(function (l) { if (l[1]) { m.off(l[0], l[1], l[2]); } else { m.off(l[0], l[2]); } });
33902
+ [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); } });
33903
+ if (m.getSource(this.id)) { m.removeSource(this.id); }
33904
+ if (this.toolbar) { m.removeControl(this.toolbar); }
33905
+ if (this.keyListener) { m.getContainer().removeEventListener('keydown', this.keyListener); }
33906
+ if (this.panOff && m.dragPan) { m.dragPan.enable(); }
33907
+ if (m.doubleClickZoom && this.dblWasOn) { m.doubleClickZoom.enable(); }
33908
+ self.map._drawTools = (self.map._drawTools || []).filter(function (t) { return t !== self; });
33909
+ };
33910
+
33911
+ DrawTool.prototype._listen = function (type, layer, fn) {
33912
+ var m = this.map.engine;
33913
+ if (layer) { m.on(type, layer, fn); } else { m.on(type, fn); }
33914
+ (this.listeners = this.listeners || []).push([type, layer, fn]);
33915
+ };
33916
+
33917
+ DrawTool.prototype._mount = function () {
33918
+ var self = this, m = this.map.engine;
33919
+ this.map._drawTools = (this.map._drawTools || []).concat([this]);
33920
+ this._addLayers();
33921
+ // The map's style changes drop every layer: the tool's come back with the map's own.
33922
+ this._listen('style.load', null, function () { self._addLayers(); });
33923
+ this._listen('mousedown', null, function (e) { self._down(e); });
33924
+ this._listen('touchstart', null, function (e) { if (e.points && e.points.length === 1) { self._down(e); } });
33925
+ this._listen('mousemove', null, function (e) { self._move(e); });
33926
+ this._listen('touchmove', null, function (e) { self._move(e); });
33927
+ this._listen('mouseup', null, function (e) { self._up(e); });
33928
+ this._listen('touchend', null, function (e) { self._up(e); });
33929
+ this._listen('click', null, function (e) { self._click(e); });
33930
+ this._listen('dblclick', null, function (e) { if (self.mode === 'polygon' || self.mode === 'line' || self.mode === 'hole') { e.preventDefault(); self._finish(); } });
33931
+ if (m.doubleClickZoom && m.doubleClickZoom.isEnabled && m.doubleClickZoom.isEnabled()) { this.dblWasOn = true; }
33932
+ var el = m.getContainer();
33933
+ this.keyListener = function (ev) {
33934
+ if (ev.key === 'Escape') { if (self.mode) { self.cancel(); } else { self.select(null); } }
33935
+ else if (ev.key === 'Enter' && self.mode) { self._finish(); }
33936
+ else if ((ev.key === 'Backspace' || ev.key === 'Delete') && self.mode && self.sketch && self.sketch.length) { self.sketch.pop(); self._render(); ev.preventDefault(); }
33937
+ else if ((ev.key === 'Backspace' || ev.key === 'Delete') && self.selected) { self.delete(); ev.preventDefault(); }
33938
+ else if ((ev.ctrlKey || ev.metaKey) && ev.key.toLowerCase() === 'z') { if (ev.shiftKey) { self.redo(); } else { self.undo(); } ev.preventDefault(); }
33939
+ };
33940
+ el.addEventListener('keydown', this.keyListener);
33941
+ if (this.o.toolbar !== false) {
33942
+ this.toolbar = this._toolbarControl();
33943
+ m.addControl(this.toolbar, typeof this.o.toolbar === 'string' ? this.o.toolbar : 'top-left');
33944
+ }
33945
+ this._render();
33946
+ };
33947
+
33948
+ DrawTool.prototype._addLayers = function () {
33949
+ var m = this.map.engine, id = this.id, c = this.color;
33950
+ if (m.getSource(id)) { return; }
33951
+ m.addSource(id, { type: 'geojson', data: { type: 'FeatureCollection', features: [] } });
33952
+ var role = function (r) { return ['==', ['get', '_role'], r]; };
33953
+ m.addLayer({ id: id + '-fill', type: 'fill', source: id, filter: ['all', ['==', ['geometry-type'], 'Polygon'], ['!', role('sketch')]],
33954
+ paint: { 'fill-color': ['coalesce', ['get', '_fill'], c], 'fill-opacity': ['case', ['==', ['get', '_selected'], true], 0.3, 0.18] } });
33955
+ m.addLayer({ id: id + '-line', type: 'line', source: id, filter: ['all', ['!=', ['geometry-type'], 'Point'], ['!', role('sketch')]],
33956
+ layout: { 'line-join': 'round', 'line-cap': 'round' },
33957
+ paint: { 'line-color': ['coalesce', ['get', '_stroke'], c], 'line-width': ['case', ['==', ['get', '_selected'], true], 3, 2] } });
33958
+ m.addLayer({ id: id + '-sketch', type: 'line', source: id, filter: role('sketch'),
33959
+ layout: { 'line-join': 'round', 'line-cap': 'round' }, paint: { 'line-color': c, 'line-width': 2, 'line-dasharray': [2, 1.5] } });
33960
+ m.addLayer({ id: id + '-mid', type: 'circle', source: id, filter: role('mid'),
33961
+ paint: { 'circle-radius': 4, 'circle-color': '#ffffff', 'circle-opacity': 0.9, 'circle-stroke-width': 1.5, 'circle-stroke-color': c } });
33962
+ m.addLayer({ id: id + '-vertex', type: 'circle', source: id, filter: ['any', role('vertex'), role('point'), role('sketch-vertex')],
33963
+ paint: { 'circle-radius': ['case', ['==', ['get', '_active'], true], 7, ['==', ['get', '_role'], 'point'], 7, 5],
33964
+ 'circle-color': ['case', ['==', ['get', '_active'], true], c, '#ffffff'], 'circle-stroke-width': 2, 'circle-stroke-color': c } });
33965
+ };
33966
+
33967
+ // What is drawn: every shape, the selected one's vertices and midpoints, and the shape being drawn.
33968
+ DrawTool.prototype._render = function () {
33969
+ var m = this.map.engine;
33970
+ if (!m || this.destroyed) { return; }
33971
+ var out = [], self = this;
33972
+ this.features.forEach(function (f) {
33973
+ var sel = f.id === self.selected;
33974
+ var props = { _id: f.id, _selected: sel };
33975
+ if (f.properties && f.properties.fill) { props._fill = f.properties.fill; }
33976
+ if (f.properties && f.properties.stroke) { props._stroke = f.properties.stroke; }
33977
+ if (f.geometry.type === 'Point') { props._role = 'point'; props._active = sel; }
33978
+ out.push({ type: 'Feature', properties: props, geometry: f.geometry });
33979
+ if (!sel || f.geometry.type === 'Point') { return; }
33980
+ if (f.properties && f.properties.shape === 'circle' && f.properties.center) {
33981
+ // A circle: one handle on its edge (east) sets the radius.
33982
+ 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] } });
33983
+ return;
33984
+ }
33985
+ ringsOf(f.geometry).forEach(function (r, ri) {
33986
+ r.coords.forEach(function (c, i) {
33987
+ var active = !!self.vertex && self.vertex.ring === ri && self.vertex.index === i;
33988
+ out.push({ type: 'Feature', properties: { _role: 'vertex', _id: f.id, _ring: ri, _index: i, _active: active }, geometry: { type: 'Point', coordinates: c } });
33989
+ var next = r.coords[i + 1] || (r.closed ? r.coords[0] : null);
33990
+ if (next && !(f.properties && f.properties.shape === 'rectangle')) {
33991
+ 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] } });
33992
+ }
33993
+ });
33994
+ });
33995
+ });
33996
+ if (this.mode && this.sketch) {
33997
+ var pts = this.sketch.concat(this.hover ? [this.hover] : []);
33998
+ if (pts.length >= 2) {
33999
+ var closed = this.mode !== 'line' && pts.length >= 3;
34000
+ out.push({ type: 'Feature', properties: { _role: 'sketch' }, geometry: { type: 'LineString', coordinates: closed ? pts.concat([pts[0]]) : pts } });
34001
+ }
34002
+ this.sketch.forEach(function (c) { out.push({ type: 'Feature', properties: { _role: 'sketch-vertex' }, geometry: { type: 'Point', coordinates: c } }); });
34003
+ }
34004
+ var src = m.getSource(this.id);
34005
+ if (src) { src.setData({ type: 'FeatureCollection', features: out }); }
34006
+ };
34007
+
34008
+ DrawTool.prototype._lngLat = function (e) { return [e.lngLat.lng, e.lngLat.lat]; };
34009
+
34010
+ // A position taken over by a vertex of another shape within SNAP_PX pixels (when snapping is on).
34011
+ DrawTool.prototype._snapped = function (e, except) {
34012
+ if (!this.snap) { return this._lngLat(e); }
34013
+ var m = this.map.engine, best = null, bestD = SNAP_PX;
34014
+ this.features.forEach(function (f) {
34015
+ if (f.id === except) { return; }
34016
+ var pts = f.geometry.type === 'Point' ? [f.geometry.coordinates] : [];
34017
+ ringsOf(f.geometry).forEach(function (r) { pts = pts.concat(r.coords); });
34018
+ pts.forEach(function (c) {
34019
+ var p = m.project(c), d = Math.sqrt(Math.pow(p.x - e.point.x, 2) + Math.pow(p.y - e.point.y, 2));
34020
+ if (d <= bestD) { bestD = d; best = c; }
34021
+ });
34022
+ });
34023
+ return best ? best.slice() : this._lngLat(e);
34024
+ };
34025
+
34026
+ DrawTool.prototype._hit = function (e, layers) {
34027
+ var m = this.map.engine, self = this;
34028
+ var ids = layers.map(function (l) { return self.id + '-' + l; }).filter(function (l) { return m.getLayer(l); });
34029
+ if (!ids.length) { return null; }
34030
+ var r = 4, box = [[e.point.x - r, e.point.y - r], [e.point.x + r, e.point.y + r]];
34031
+ var hits = m.queryRenderedFeatures(box, { layers: ids }) || [];
34032
+ return hits[0] || null;
34033
+ };
34034
+
34035
+ DrawTool.prototype._pan = function (on) {
34036
+ var m = this.map.engine;
34037
+ if (!m.dragPan) { return; }
34038
+ if (on && this.panOff) { m.dragPan.enable(); this.panOff = false; }
34039
+ else if (!on && !this.panOff && (!m.dragPan.isEnabled || m.dragPan.isEnabled())) { m.dragPan.disable(); this.panOff = true; }
34040
+ };
34041
+
34042
+ DrawTool.prototype._down = function (e) {
34043
+ if (e.originalEvent && e.originalEvent.button !== undefined && e.originalEvent.button !== 0) { return; }
34044
+ var self = this;
34045
+ if (this.mode === 'rectangle' || this.mode === 'circle') {
34046
+ e.preventDefault();
34047
+ this._pan(false);
34048
+ this.drag = { kind: this.mode, start: this._snapped(e) };
34049
+ return;
34050
+ }
34051
+ if (this.mode) { return; }
34052
+ if (!this.selected) { return; }
34053
+ var f = this._find(this.selected);
34054
+ var hit = this._hit(e, ['vertex', 'mid']);
34055
+ if (hit && hit.properties._id === this.selected) {
34056
+ e.preventDefault();
34057
+ this._pan(false);
34058
+ var p = hit.properties;
34059
+ if (p._radius) {
34060
+ this._record();
34061
+ this.drag = { kind: 'radius', moved: false };
34062
+ return;
34063
+ }
34064
+ if (p._role === 'mid') {
34065
+ // A midpoint dragged becomes a new vertex.
34066
+ this._record();
34067
+ var rings = ringsOf(f.geometry), r = rings[p._ring], coords = r.coords.slice();
34068
+ coords.splice(p._index, 0, hit.geometry.coordinates.slice());
34069
+ setRing(f.geometry, r.path, coords);
34070
+ this.vertex = { ring: p._ring, index: p._index };
34071
+ } else {
34072
+ this._record();
34073
+ this.vertex = { ring: p._ring, index: p._index };
34074
+ }
34075
+ this.drag = { kind: 'vertex', moved: false };
34076
+ this._render();
34077
+ return;
34078
+ }
34079
+ var body = this._hit(e, ['fill', 'line', 'vertex']);
34080
+ if (body && body.properties._id === this.selected) {
34081
+ e.preventDefault();
34082
+ this._pan(false);
34083
+ this._record();
34084
+ this.drag = { kind: 'move', last: this._lngLat(e), moved: false };
34085
+ self.vertex = null;
34086
+ }
34087
+ };
34088
+
34089
+ DrawTool.prototype._move = function (e) {
34090
+ if (this.mode && this.sketch && !this.drag) { this.hover = this._snapped(e); this._render(); }
34091
+ var d = this.drag;
34092
+ if (!d) { return; }
34093
+ var f = this.selected && this._find(this.selected);
34094
+ if (d.kind === 'rectangle' || d.kind === 'circle') {
34095
+ d.end = this._lngLat(e);
34096
+ var shape = this._dragShape(d);
34097
+ this.sketch = shape ? openRing(shape) : [];
34098
+ this.hover = null;
34099
+ this._render();
34100
+ return;
34101
+ }
34102
+ if (!f) { return; }
34103
+ d.moved = true;
34104
+ if (d.kind === 'radius') {
34105
+ f.properties.radius = interop.geo.distance(f.properties.center, this._lngLat(e));
34106
+ f.geometry.coordinates = [circleRing(f.properties.center, f.properties.radius)];
34107
+ } else if (d.kind === 'vertex' && f.properties && f.properties.shape === 'rectangle') {
34108
+ // A rectangle stays a rectangle: the opposite corner stays, the dragged one follows the pointer.
34109
+ var cs = ringsOf(f.geometry)[0].coords, opp = cs[(this.vertex.index + 2) % 4], at = this._snapped(e, f.id);
34110
+ var rect = [[opp[0], opp[1]], [at[0], opp[1]], [at[0], at[1]], [opp[0], at[1]]];
34111
+ // Keep the dragged corner at its index.
34112
+ var shift = (this.vertex.index + 2) % 4, ordered = [];
34113
+ for (var q = 0; q < 4; q++) { ordered[(shift + q) % 4] = rect[q]; }
34114
+ f.geometry.coordinates = [closeRing(ordered)];
34115
+ } else if (d.kind === 'vertex') {
34116
+ var rings = ringsOf(f.geometry), r = rings[this.vertex.ring], coords = r.coords.slice();
34117
+ coords[this.vertex.index] = this._snapped(e, f.id);
34118
+ setRing(f.geometry, r.path, coords);
34119
+ } else if (d.kind === 'move') {
34120
+ var now = this._lngLat(e);
34121
+ if (f.properties && f.properties.shape === 'circle' && f.properties.center) {
34122
+ f.properties.center = [f.properties.center[0] + now[0] - d.last[0], f.properties.center[1] + now[1] - d.last[1]];
34123
+ }
34124
+ moveGeometry(f.geometry, now[0] - d.last[0], now[1] - d.last[1]);
34125
+ d.last = now;
34126
+ }
34127
+ this._render();
34128
+ };
34129
+
34130
+ DrawTool.prototype._dragShape = function (d) {
34131
+ if (!d.end) { return null; }
34132
+ if (d.kind === 'rectangle') {
34133
+ var a = d.start, b = d.end;
34134
+ return [[a[0], a[1]], [b[0], a[1]], [b[0], b[1]], [a[0], b[1]], [a[0], a[1]]];
34135
+ }
34136
+ var radius = interop.geo.distance(d.start, d.end);
34137
+ return radius > 0 ? circleRing(d.start, radius) : null;
34138
+ };
34139
+
34140
+ DrawTool.prototype._up = function (e) {
34141
+ var d = this.drag;
34142
+ if (!d) { return; }
34143
+ this.drag = null;
34144
+ this._pan(true);
34145
+ this._suppressClick = true;
34146
+ var self = this;
34147
+ setTimeout(function () { self._suppressClick = false; }, 0);
34148
+ if (d.kind === 'rectangle' || d.kind === 'circle') {
34149
+ d.end = this._lngLat(e);
34150
+ var ring = this._dragShape(d);
34151
+ var mode = this.mode;
34152
+ this.mode = null; this.sketch = null; this.hover = null;
34153
+ if (ring && Math.abs(ring[0][0] - ring[2][0]) + Math.abs(ring[0][1] - ring[2][1]) > 0) {
34154
+ var props = mode === 'circle' ? { shape: 'circle', center: d.start, radius: interop.geo.distance(d.start, d.end) } : { shape: 'rectangle' };
34155
+ this._add({ type: 'Feature', properties: props, geometry: { type: 'Polygon', coordinates: [ring] } });
34156
+ } else { this._render(); this._renderToolbar(); }
34157
+ return;
34158
+ }
34159
+ if (d.moved) { this._emit('edited', this._find(this.selected)); } else { this.undoStack.pop(); }
34160
+ this._render();
34161
+ };
34162
+
34163
+ DrawTool.prototype._click = function (e) {
34164
+ if (this._suppressClick) { return; }
34165
+ var self = this;
34166
+ if (this.mode === 'point') { this.mode = null; this.sketch = null; this._add({ type: 'Feature', properties: {}, geometry: { type: 'Point', coordinates: this._snapped(e) } }); return; }
34167
+ if (this.mode === 'polygon' || this.mode === 'line' || this.mode === 'hole') {
34168
+ var at = this._snapped(e);
34169
+ // A click on the first vertex closes a polygon.
34170
+ if (this.mode !== 'line' && this.sketch.length >= 3) {
34171
+ var first = this.map.engine.project(this.sketch[0]);
34172
+ if (Math.abs(first.x - e.point.x) <= SNAP_PX && Math.abs(first.y - e.point.y) <= SNAP_PX) { this._finish(); return; }
34173
+ }
34174
+ var last = this.sketch[this.sketch.length - 1];
34175
+ if (!last || last[0] !== at[0] || last[1] !== at[1]) { this.sketch.push(at); }
34176
+ this._render();
34177
+ return;
34178
+ }
34179
+ if (this.mode) { return; }
34180
+ // Not drawing: a click selects the shape under it (or a vertex of the selected one), elsewhere deselects.
34181
+ var v = this.selected && this._hit(e, ['vertex']);
34182
+ if (v && v.properties._id === this.selected && v.properties._role === 'vertex') {
34183
+ this.vertex = { ring: v.properties._ring, index: v.properties._index };
34184
+ this._render();
34185
+ return;
34186
+ }
34187
+ var hit = this._hit(e, ['vertex', 'line', 'fill']);
34188
+ self.select(hit ? hit.properties._id : null);
34189
+ };
34190
+
34191
+ DrawTool.prototype._finish = function () {
34192
+ var mode = this.mode, pts = (this.sketch || []).slice();
34193
+ this.mode = null; this.sketch = null; this.hover = null;
34194
+ if (mode === 'line' && pts.length >= 2) { this._add({ type: 'Feature', properties: {}, geometry: { type: 'LineString', coordinates: pts } }); return; }
34195
+ if (mode === 'polygon' && pts.length >= 3) { this._add({ type: 'Feature', properties: {}, geometry: { type: 'Polygon', coordinates: [closeRing(pts)] } }); return; }
34196
+ if (mode === 'hole' && pts.length >= 3) {
34197
+ var f = this._find(this.selected);
34198
+ if (f && f.geometry.type === 'Polygon') {
34199
+ this._record();
34200
+ f.geometry.coordinates.push(closeRing(pts));
34201
+ this._render(); this._renderToolbar();
34202
+ this._emit('edited', f);
34203
+ return;
34204
+ }
34205
+ }
34206
+ this._render();
34207
+ this._renderToolbar();
34208
+ };
34209
+
34210
+ DrawTool.prototype._add = function (feature) {
34211
+ this._record();
34212
+ var f = this._own(feature);
34213
+ this.features.push(f);
34214
+ this.selected = f.geometry.type === 'Point' ? null : f.id;
34215
+ this.vertex = null;
34216
+ this._render();
34217
+ this._renderToolbar();
34218
+ this._emit('created', f);
34219
+ };
34220
+
34221
+ DrawTool.prototype._toolbarControl = function () {
34222
+ var self = this;
34223
+ return {
34224
+ onAdd: function (m) {
34225
+ var doc = m.getContainer().ownerDocument;
34226
+ var el = doc.createElement('div');
34227
+ el.className = 'maplibregl-ctrl maplibregl-ctrl-group smap-draw';
34228
+ self.toolbarEl = el;
34229
+ self._renderToolbar();
34230
+ return el;
34231
+ },
34232
+ onRemove: function () { if (self.toolbarEl && self.toolbarEl.parentNode) { self.toolbarEl.parentNode.removeChild(self.toolbarEl); } self.toolbarEl = null; },
34233
+ };
34234
+ };
34235
+
34236
+ var DRAW_ICONS = {
34237
+ polygon: '<path d="M5 7l7-4 7 5-2 10H7z"/>', rectangle: '<rect x="4" y="6" width="16" height="12"/>',
34238
+ 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"/>',
34239
+ 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"/>',
34240
+ 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"/>',
34241
+ };
34242
+
34243
+ DrawTool.prototype._renderToolbar = function () {
34244
+ var el = this.toolbarEl;
34245
+ if (!el) { return; }
34246
+ var self = this, doc = el.ownerDocument;
34247
+ while (el.firstChild) { el.removeChild(el.firstChild); }
34248
+ var selectedPolygon = this.selected && this._find(this.selected) && this._find(this.selected).geometry.type === 'Polygon' && !(this._find(this.selected).properties.shape);
34249
+ var buttons = this.modes.slice();
34250
+ if (selectedPolygon) { buttons.push('hole'); }
34251
+ buttons = buttons.concat(['delete', 'undo', 'redo']);
34252
+ buttons.forEach(function (k) {
34253
+ var b = doc.createElement('button');
34254
+ b.type = 'button';
34255
+ b.className = 'smap-draw-' + k;
34256
+ b.title = self.text[k];
34257
+ b.setAttribute('aria-label', self.text[k]);
34258
+ 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>';
34259
+ if (DRAW_MODES.indexOf(k) >= 0 || k === 'hole') {
34260
+ b.setAttribute('aria-pressed', self.mode === k ? 'true' : 'false');
34261
+ b.addEventListener('click', function () { if (self.mode === k) { self.cancel(); } else { self.start(k); } });
34262
+ } else if (k === 'delete') {
34263
+ b.disabled = !self.selected;
34264
+ b.addEventListener('click', function () { self.delete(); });
34265
+ } else {
34266
+ b.disabled = k === 'undo' ? !self.undoStack.length : !self.redoStack.length;
34267
+ b.addEventListener('click', function () { self[k](); });
34268
+ }
34269
+ el.appendChild(b);
34270
+ });
34271
+ };
34272
+
34273
+ /**
34274
+ * Selects features by drawing on the map: 'box' (press and drag) or 'lasso' (press and draw a free shape). Resolves
34275
+ * with { features: { layerId: [features] }, geometry } once the shape is drawn, or null when Escape cancels it.
34276
+ * A point (or custom marker) counts when it is inside; a line or area when any of its vertices is.
34277
+ * @param {Object} [o] mode ('box' default, 'lasso'), layers (default every point, custom marker, line and area layer)
34278
+ */
34279
+ SMap.prototype.selectArea = function (o) {
34280
+ o = o || {};
34281
+ var self = this;
34282
+ var mode = o.mode === 'lasso' ? 'lasso' : 'box';
34283
+ return this.ready.then(function () {
34284
+ return new Promise(function (resolve) {
34285
+ var m = self.engine;
34286
+ var overlay = self._markerOverlay(), doc = overlay.ownerDocument;
34287
+ var svgNs = 'http://www.w3.org/2000/svg';
34288
+ var svg = doc.createElementNS(svgNs, 'svg');
34289
+ svg.setAttribute('class', 'smap-select');
34290
+ var shape = doc.createElementNS(svgNs, mode === 'box' ? 'rect' : 'polyline');
34291
+ svg.appendChild(shape);
34292
+ var points = null, panWasOn = !!(m.dragPan && (!m.dragPan.isEnabled || m.dragPan.isEnabled()));
34293
+ if (panWasOn) { m.dragPan.disable(); }
34294
+ if (m.boxZoom && m.boxZoom.disable) { m.boxZoom.disable(); }
34295
+ m.getCanvas().style.cursor = 'crosshair';
34296
+ var finish = function (result) {
34297
+ m.off('mousedown', down); m.off('mousemove', move); m.off('mouseup', up);
34298
+ m.off('touchstart', down); m.off('touchmove', move); m.off('touchend', up);
34299
+ m.getContainer().removeEventListener('keydown', key);
34300
+ if (svg.parentNode) { svg.parentNode.removeChild(svg); }
34301
+ if (panWasOn) { m.dragPan.enable(); }
34302
+ if (m.boxZoom && m.boxZoom.enable) { m.boxZoom.enable(); }
34303
+ m.getCanvas().style.cursor = '';
34304
+ resolve(result);
34305
+ };
34306
+ var draw = function () {
34307
+ if (mode === 'box') {
34308
+ var a = points[0], b = points[points.length - 1];
34309
+ shape.setAttribute('x', Math.min(a.x, b.x)); shape.setAttribute('y', Math.min(a.y, b.y));
34310
+ shape.setAttribute('width', Math.abs(a.x - b.x)); shape.setAttribute('height', Math.abs(a.y - b.y));
34311
+ } else {
34312
+ shape.setAttribute('points', points.map(function (p) { return p.x + ',' + p.y; }).join(' '));
34313
+ }
34314
+ };
34315
+ var down = function (e) { e.preventDefault(); points = [e.point]; overlay.appendChild(svg); draw(); };
34316
+ var move = function (e) { if (!points) { return; } if (mode === 'box') { points = [points[0], e.point]; } else { points.push(e.point); } draw(); };
34317
+ var up = function (e) {
34318
+ if (!points) { return; }
34319
+ if (mode === 'box') { points = [points[0], e.point]; }
34320
+ var ring;
34321
+ if (mode === 'box') {
34322
+ var a = points[0], b = points[1];
34323
+ ring = [[a.x, a.y], [b.x, a.y], [b.x, b.y], [a.x, b.y]];
34324
+ } else {
34325
+ ring = points.map(function (p) { return [p.x, p.y]; });
34326
+ }
34327
+ var geoRing = ring.map(function (p) { var ll = m.unproject(p); return [ll.lng, ll.lat]; });
34328
+ var geometry = { type: 'Polygon', coordinates: [closeRing(geoRing)] };
34329
+ finish({ features: self._featuresIn(ring, o.layers), geometry: geometry });
34330
+ };
34331
+ var key = function (ev) { if (ev.key === 'Escape') { finish(null); } };
34332
+ m.on('mousedown', down); m.on('mousemove', move); m.on('mouseup', up);
34333
+ m.on('touchstart', down); m.on('touchmove', move); m.on('touchend', up);
34334
+ m.getContainer().addEventListener('keydown', key);
34335
+ });
34336
+ });
34337
+ };
34338
+
34339
+ // The features of the map's layers with a vertex inside a ring of screen points (projected now).
34340
+ SMap.prototype._featuresIn = function (ring, layers) {
34341
+ var self = this, m = this.engine, out = {};
34342
+ var xs = ring.map(function (p) { return p[0]; }), ys = ring.map(function (p) { return p[1]; });
34343
+ 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);
34344
+ var inside = function (c) {
34345
+ var p = m.project(c);
34346
+ if (p.x < minX || p.x > maxX || p.y < minY || p.y > maxY) { return false; }
34347
+ return interop.geo.pointInPolygon([p.x, p.y], ring);
34348
+ };
34349
+ (layers || this._order).forEach(function (id) {
34350
+ var def = self._layers[id];
34351
+ if (!def || def.hidden || !def.data || ['points', 'custom', 'lines', 'polygons', 'heatmap'].indexOf(def.kind) < 0) { return; }
34352
+ var hits = def.data.features.filter(function (f) {
34353
+ var found = false;
34354
+ (function walk(c) { if (found || !c) { return; } if (typeof c[0] === 'number') { found = inside(c); } else { c.forEach(walk); } })(f.geometry && f.geometry.coordinates);
34355
+ return found;
34356
+ });
34357
+ if (hits.length) { out[id] = hits; }
34358
+ });
34359
+ return out;
34360
+ };
34361
+
34362
+ // ------------------------------------------------------------------ controls (G8): own controls, base imagery, layer switcher
34363
+
34364
+ /**
34365
+ * Puts an element or an engine control in a corner of the map without making it a tool (it is never hidden by the
34366
+ * tools control). An element returns where the page had it when removed.
34367
+ * @param {Element|Object} target
34368
+ * @param {string} [position] 'top-left', 'top-right' (default), 'bottom-left', 'bottom-right'
34369
+ */
34370
+ SMap.prototype.addControl = function (target, position) {
34371
+ position = position || 'top-right';
34372
+ if (TOOL_CORNERS.indexOf(position) < 0) { throw new Error('sMap: unknown control position "' + position + '"'); }
34373
+ if (!isElement(target) && !(target && typeof target.onAdd === 'function')) { throw new Error('sMap: a control is an element or an engine control'); }
34374
+ this._controls = this._controls || [];
34375
+ var holder = { position: position, el: null };
34376
+ var control = isElement(target) ? elementControl(holder, target) : target;
34377
+ this._controls.push({ target: target, control: control, position: position });
34378
+ var self = this;
34379
+ if (this.engine) { this.engine.addControl(control, position); } else { this.ready.then(function () { self.engine.addControl(control, position); }); }
34380
+ return this;
34381
+ };
34382
+
34383
+ SMap.prototype.removeControl = function (target) {
34384
+ var list = this._controls || [];
34385
+ for (var i = 0; i < list.length; i++) {
34386
+ if (list[i].target !== target) { continue; }
34387
+ if (this.engine) { this.engine.removeControl(list[i].control); }
34388
+ list.splice(i, 1);
34389
+ break;
34390
+ }
34391
+ return this;
34392
+ };
34393
+
34394
+ var BASE_RASTER = 'smap-base-imagery';
34395
+
34396
+ /**
34397
+ * Imagery (satellite, aerial, a scanned map, …) in place of the street map: raster tiles drawn over the basemap's
34398
+ * land, water and roads, under its labels — which stay with `labels: true` (a hybrid map) and are hidden otherwise.
34399
+ * Your layers stay on top, in their slots. null goes back to the street map.
34400
+ * @param {Object|null} imagery { tiles: [url with {z}/{x}/{y}], tileSize (256), minzoom, maxzoom, attribution,
34401
+ * scheme ('xyz' | 'tms'), labels (default false) }
34402
+ */
34403
+ SMap.prototype.setBaseImagery = function (imagery) {
34404
+ if (imagery && (!Array.isArray(imagery.tiles) || !imagery.tiles.length)) { throw new Error('sMap: base imagery needs tiles'); }
34405
+ // Google's and Bing's tiles only through their own terms: Google's with setGoogleBase (M31, M66).
34406
+ if (imagery) { interop.refuseForbidden(imagery.tiles); }
34407
+ return this._setBaseImagery(imagery);
34408
+ };
34409
+
34410
+ SMap.prototype._setBaseImagery = function (imagery) {
34411
+ this._baseImagery = imagery ? Object.assign({}, imagery) : null;
34412
+ if (this.engine && this._styleReady) { this._applyBaseImagery(); }
34413
+ return this;
34414
+ };
34415
+
34416
+ // Whether a style (a scheme, 'custom:<id>', a URL or an object) is the one shown now.
34417
+ SMap.prototype._isStyle = function (style) {
34418
+ if (typeof style === 'string' && FLAVORS.indexOf(style) >= 0) { return !this._customStyle && !this._serverStyle && this._flavor === style; }
34419
+ if (typeof style === 'string' && style.indexOf(CUSTOM_PREFIX) === 0) { return this._serverStyle === style; }
34420
+ return this._customStyle === style;
34421
+ };
34422
+
34423
+ SMap.prototype.baseImagery = function () { return this._baseImagery ? Object.assign({}, this._baseImagery) : null; };
34424
+
34425
+ SMap.prototype._applyBaseImagery = function () {
34426
+ var m = this.engine, b = this._baseImagery;
34427
+ if (m.getLayer(BASE_RASTER)) { m.removeLayer(BASE_RASTER); }
34428
+ if (m.getSource(BASE_RASTER)) { m.removeSource(BASE_RASTER); }
34429
+ var anchors = this.slots();
34430
+ var labelsAt = anchors.labels;
34431
+ // The basemap's labels: every basemap layer from where the labels slot begins.
34432
+ var ids = this._basemapIds.filter(function (x) { return m.getLayer(x); });
34433
+ var from = labelsAt ? ids.indexOf(labelsAt) : -1;
34434
+ var labelIds = from >= 0 ? ids.slice(from) : [];
34435
+ var hidden = this._imageryHid || [];
34436
+ hidden.forEach(function (x) { if (m.getLayer(x)) { m.setLayoutProperty(x, 'visibility', 'visible'); } });
34437
+ this._imageryHid = [];
34438
+ if (!b) { return; }
34439
+ var source = { type: 'raster', tiles: b.tiles.slice(), tileSize: b.tileSize || 256 };
34440
+ if (b.minzoom !== undefined) { source.minzoom = b.minzoom; }
34441
+ if (b.maxzoom !== undefined) { source.maxzoom = b.maxzoom; }
34442
+ if (b.attribution) { source.attribution = b.attribution; }
34443
+ if (b.scheme) { source.scheme = b.scheme; }
34444
+ m.addSource(BASE_RASTER, source);
34445
+ m.addLayer({ id: BASE_RASTER, type: 'raster', source: BASE_RASTER }, labelsAt || undefined);
34446
+ if (!b.labels) {
34447
+ var self = this;
34448
+ labelIds.forEach(function (x) {
34449
+ if (m.getLayoutProperty && m.getLayoutProperty(x, 'visibility') === 'none') { return; }
34450
+ m.setLayoutProperty(x, 'visibility', 'none');
34451
+ self._imageryHid.push(x);
34452
+ });
34453
+ }
34454
+ };
34455
+
34456
+ // ---- 3D models (G12): glTF models at points, drawn with three.js (handed over once with sMap.useThree)
34457
+
34458
+
34459
+ /**
34460
+ * glTF models at points (vehicles, buildings, equipment), drawn in the map's 3D view and turned to each feature's
34461
+ * heading. Needs three.js: call sMap.useThree(THREE, GLTFLoader) once first.
34462
+ * @param {Object} o model (a .glb / .gltf URL), size (metres per model unit, default 1; or per feature),
34463
+ * heading (degrees clockwise from north, default 0; or per feature, e.g. { property: 'bearing' }),
34464
+ * altitude (metres above the ground, default 0), rotate ([x, y, z] degrees turning the model upright and to
34465
+ * face north before the heading; default [90, 0, 180], right for a model whose up is +Y and front +Z),
34466
+ * idProperty, minzoom, slot, before, zIndex
34467
+ */
34468
+ SMap.prototype.addModels = function (id, data, o) {
34469
+ if (!interop.getThree()) { throw new Error('sMap: call sMap.useThree(THREE, GLTFLoader) before addModels'); }
34470
+ if (!o || !o.model) { throw new Error('sMap: addModels needs a model URL'); }
34471
+ this._define(id, { kind: 'models', data: toFeatureCollection(data), o: o });
34472
+ return this;
34473
+ };
34474
+
34475
+ SMap.prototype._modelLayer = function (id, def) {
34476
+ var self = this, three = interop.getThree(), T = three.THREE, o = def.o;
34477
+ var deg = Math.PI / 180;
34478
+ var base = o.rotate || [90, 0, 180];
34479
+ var baseMatrix = new T.Matrix4().makeRotationFromEuler(new T.Euler(base[0] * deg, base[1] * deg, base[2] * deg, 'ZYX'));
34480
+ var layer = {
34481
+ id: 'smap-' + id + '-models', type: 'custom', renderingMode: '3d',
34482
+ onAdd: function (map, gl) {
34483
+ this.map = map;
34484
+ this.scene = new T.Scene();
34485
+ this.camera = new T.Camera();
34486
+ this.renderer = new T.WebGLRenderer({ canvas: map.getCanvas(), context: gl, antialias: true });
34487
+ this.renderer.autoClear = false;
34488
+ this.scene.add(new T.AmbientLight(0xffffff, 0.8));
34489
+ var sun = new T.DirectionalLight(0xffffff, 0.6);
34490
+ sun.position.set(0.3, -0.5, 1);
34491
+ this.scene.add(sun);
34492
+ this.objects = {};
34493
+ var me = this;
34494
+ new three.GLTFLoader().load(o.model, function (gltf) {
34495
+ me.prototypeObject = gltf.scene;
34496
+ map.triggerRepaint();
34497
+ }, undefined, function (error) { self._reportError(error); });
34498
+ },
34499
+ render: function (gl, args) {
34500
+ if (!this.prototypeObject) { return; }
34501
+ var matrix = args && args.defaultProjectionData ? args.defaultProjectionData.mainMatrix : (args && args.modelViewProjectionMatrix) || args;
34502
+ var seen = {}, me = this, cur = self._layers[id];
34503
+ if (!cur) { return; }
34504
+ cur.data.features.forEach(function (f, i) {
34505
+ var at = pointOf(f);
34506
+ if (!at) { return; }
34507
+ var key = featureKey(cur, f, i);
34508
+ seen[key] = true;
34509
+ var obj = me.objects[key];
34510
+ if (!obj) { obj = me.objects[key] = me.prototypeObject.clone(true); obj.matrixAutoUpdate = false; me.scene.add(obj); }
34511
+ var props = f.properties || {};
34512
+ var mc = engine.MercatorCoordinate.fromLngLat(at, +plainValue(o.altitude, props, f, 0) || 0);
34513
+ var k = mc.meterInMercatorCoordinateUnits() * (+plainValue(o.size, props, f, 1) || 1);
34514
+ var heading = (+plainValue(o.heading, props, f, 0) || 0) * deg;
34515
+ obj.matrix.copy(new T.Matrix4().makeTranslation(mc.x, mc.y, mc.z)
34516
+ .multiply(new T.Matrix4().makeScale(k, -k, k))
34517
+ .multiply(new T.Matrix4().makeRotationZ(heading))
34518
+ .multiply(baseMatrix));
34519
+ obj.matrixWorldNeedsUpdate = true;
34520
+ });
34521
+ Object.keys(this.objects).forEach(function (key) { if (!seen[key]) { me.scene.remove(me.objects[key]); delete me.objects[key]; } });
34522
+ this.camera.projectionMatrix = new T.Matrix4().fromArray(matrix);
34523
+ this.renderer.resetState();
34524
+ this.renderer.render(this.scene, this.camera);
34525
+ },
34526
+ onRemove: function () { if (this.renderer && this.renderer.dispose) { this.renderer.dispose(); } },
34527
+ };
34528
+ return layer;
34529
+ };
34530
+
34531
+ var GOOGLE_LOGO = 'https://maps.gstatic.com/mapfiles/api-3/images/google_white5.png';
34532
+
34533
+ /**
34534
+ * Google's base maps from the Map Tiles API (G10), read straight from Google with a session your server made with
34535
+ * your own Google key; shown in place of the street map like setBaseImagery. As Google's terms ask, the Google logo
34536
+ * is shown and the copyright of the area in view is asked of Google after each move. null takes it off.
34537
+ * @param {Object|null} g { session, key } (or `tiles`: the tile URL template, and `viewport`: the viewport address up
34538
+ * to its query, both with session and key), type ('roadmap' | 'satellite', for the attribution only),
34539
+ * maxzoom (22), labels (keep the street map's labels over Google's imagery; default false),
34540
+ * onFail() (called when Google's first tiles fail and none loads: show your own map instead)
34541
+ */
34542
+ SMap.prototype.setGoogleBase = function (g) {
34543
+ var self = this;
34544
+ var run = function () {
34545
+ var m = self.engine;
34546
+ if (self._google) {
34547
+ if (self._google.control) { m.removeControl(self._google.control); }
34548
+ self._google.off.forEach(function (x) { m.off(x[0], x[1]); });
34549
+ self._google = null;
34550
+ }
34551
+ if (!g) { self._setBaseImagery(null); return; }
34552
+ if (!g.tiles && !(g.session && g.key)) { throw new Error('sMap: a Google layer needs session and key, or tiles'); }
34553
+ var q = g.session ? 'session=' + encodeURIComponent(g.session) + '&key=' + encodeURIComponent(g.key) : '';
34554
+ var tiles = g.tiles || 'https://tile.googleapis.com/v1/2dtiles/{z}/{x}/{y}?' + q;
34555
+ var viewport = g.viewport || (q ? 'https://tile.googleapis.com/tile/v1/viewport?' + q : null);
34556
+ var state = { off: [], control: null, text: null, errors: 0, loaded: 0, failed: false };
34557
+ self._google = state;
34558
+ self._setBaseImagery({ tiles: [tiles], tileSize: 256, maxzoom: g.maxzoom || 22, labels: !!g.labels });
34559
+ // The logo and the copyright of the area in view, bottom left.
34560
+ var doc = m.getContainer().ownerDocument;
34561
+ var box = doc.createElement('div');
34562
+ box.className = 'smap-google';
34563
+ var logo = doc.createElement('img');
34564
+ logo.src = GOOGLE_LOGO;
34565
+ logo.alt = 'Google';
34566
+ var text = doc.createElement('span');
34567
+ text.className = 'smap-google-copyright';
34568
+ text.textContent = 'Google';
34569
+ box.appendChild(logo);
34570
+ box.appendChild(text);
34571
+ state.text = text;
34572
+ state.control = { onAdd: function () { return box; }, onRemove: function () { if (box.parentNode) { box.parentNode.removeChild(box); } } };
34573
+ m.addControl(state.control, 'bottom-left');
34574
+ var seq = 0;
34575
+ var copyright = function () {
34576
+ if (!viewport || self._google !== state || typeof fetch !== 'function') { return; }
34577
+ var b = m.getBounds(), mine = ++seq;
34578
+ var url = viewport + (viewport.indexOf('?') >= 0 ? '&' : '?') + 'zoom=' + Math.round(m.getZoom() + 1) +
34579
+ '&north=' + b.getNorth() + '&south=' + b.getSouth() + '&east=' + b.getEast() + '&west=' + b.getWest();
34580
+ fetch(url).then(function (r) { return r.ok ? r.json() : null; }).then(function (v) {
34581
+ if (mine === seq && self._google === state) { text.textContent = (v && v.copyright) || 'Google'; }
34582
+ }, function () {});
34583
+ };
34584
+ var watch = function (e) {
34585
+ if (!e || e.sourceId !== BASE_RASTER || state.failed) { return; }
34586
+ if (e.type === 'error') { state.errors += 1; } else if (e.tile) { state.loaded += 1; }
34587
+ if (state.errors >= 4 && state.loaded === 0) {
34588
+ state.failed = true;
34589
+ if (g.onFail) { g.onFail(); }
34590
+ }
34591
+ };
34592
+ m.on('moveend', copyright); state.off.push(['moveend', copyright]);
34593
+ m.on('error', watch); state.off.push(['error', watch]);
34594
+ m.on('sourcedata', watch); state.off.push(['sourcedata', watch]);
34595
+ copyright();
34596
+ };
34597
+ if (this.engine) { run(); } else { this.ready.then(run); }
34598
+ return this;
34599
+ };
34600
+
34601
+ var LAYERS_ICON = '<svg viewBox="0 0 24 24" width="18" height="18" aria-hidden="true" focusable="false" fill="none" ' +
34602
+ 'stroke="currentColor" stroke-width="2" stroke-linejoin="round"><path d="M12 3 2 8l10 5 10-5-10-5z"/>' +
34603
+ '<path d="m2 13 10 5 10-5"/></svg>';
34604
+
34605
+ /**
34606
+ * The layer switcher: one button opening a list of base maps (one at a time) and overlays (each on or off).
34607
+ * base: [{ id, label, style? (a scheme, 'custom:…' or a style URL), imagery? (as setBaseImagery) }]
34608
+ * overlays: [{ id, label, layers: [layer ids], visible? }]
34609
+ * value (the base shown at first), title (the button's label), onChange({ base, overlays: [ids shown] })
34610
+ */
34611
+ function layersControl(map, opts) {
34612
+ var base = opts.base || [];
34613
+ var overlays = opts.overlays || [];
34614
+ var current = opts.value || (base[0] && base[0].id) || null;
34615
+ var shown = {};
34616
+ overlays.forEach(function (ov) { shown[ov.id] = ov.visible !== false; });
34617
+ var el = null, button = null, panel = null;
34618
+ function report() {
34619
+ if (opts.onChange) { opts.onChange({ base: current, overlays: overlays.filter(function (ov) { return shown[ov.id]; }).map(function (ov) { return ov.id; }) }); }
34620
+ }
34621
+ function applyBase(entry) {
34622
+ if (!entry) { return; }
34623
+ // The scheme already shown is not loaded again (no flicker when only the imagery changes).
34624
+ if (entry.style !== undefined && entry.style !== null && !map._isStyle(entry.style)) { map.setStyle(entry.style); }
34625
+ map.setBaseImagery(entry.imagery || null);
34626
+ }
34627
+ function applyOverlay(ov) { (ov.layers || []).forEach(function (id) { map.setVisible(id, !!shown[ov.id]); }); }
34628
+ function render() {
34629
+ var doc = el.ownerDocument;
34630
+ while (panel.firstChild) { panel.removeChild(panel.firstChild); }
34631
+ var name = 'smap-base-' + Math.random().toString(36).slice(2);
34632
+ base.forEach(function (entry) {
34633
+ var row = doc.createElement('label');
34634
+ row.className = 'smap-layers-row';
34635
+ var input = doc.createElement('input');
34636
+ input.type = 'radio'; input.name = name; input.value = entry.id; input.checked = entry.id === current;
34637
+ input.addEventListener('change', function () { current = entry.id; applyBase(entry); report(); });
34638
+ row.appendChild(input);
34639
+ row.appendChild(doc.createTextNode(' ' + (entry.label || entry.id)));
34640
+ panel.appendChild(row);
34641
+ });
34642
+ if (base.length && overlays.length) { var hr = doc.createElement('div'); hr.className = 'smap-layers-sep'; panel.appendChild(hr); }
34643
+ overlays.forEach(function (ov) {
34644
+ var row = doc.createElement('label');
34645
+ row.className = 'smap-layers-row';
34646
+ var input = doc.createElement('input');
34647
+ input.type = 'checkbox'; input.value = ov.id; input.checked = !!shown[ov.id];
34648
+ input.addEventListener('change', function () { shown[ov.id] = input.checked; applyOverlay(ov); report(); });
34649
+ row.appendChild(input);
34650
+ row.appendChild(doc.createTextNode(' ' + (ov.label || ov.id)));
34651
+ panel.appendChild(row);
34652
+ });
34653
+ }
34654
+ function open(on) { panel.hidden = !on; button.setAttribute('aria-expanded', on ? 'true' : 'false'); }
34655
+ function close() { if (panel && !panel.hidden) { open(false); } }
34656
+ return {
34657
+ onAdd: function (m) {
34658
+ var doc = m.getContainer().ownerDocument;
34659
+ el = doc.createElement('div');
34660
+ el.className = 'maplibregl-ctrl maplibregl-ctrl-group smap-layers';
34661
+ button = doc.createElement('button');
34662
+ button.type = 'button';
34663
+ button.className = 'smap-layers-button';
34664
+ button.innerHTML = LAYERS_ICON;
34665
+ button.title = opts.title || 'Layers';
34666
+ button.setAttribute('aria-label', opts.title || 'Layers');
34667
+ button.setAttribute('aria-haspopup', 'true');
34668
+ button.addEventListener('click', function () { open(panel.hidden); });
34669
+ panel = doc.createElement('div');
34670
+ panel.className = 'smap-layers-panel';
34671
+ el.appendChild(button);
34672
+ el.appendChild(panel);
34673
+ render();
34674
+ open(false);
34675
+ m.on('click', close);
34676
+ // The starting state: the chosen base and every overlay as given.
34677
+ var entry = base.filter(function (b) { return b.id === current; })[0];
34678
+ if (entry && entry.imagery) { map.setBaseImagery(entry.imagery); }
34679
+ overlays.forEach(function (ov) { if (!shown[ov.id]) { applyOverlay(ov); } });
34680
+ return el;
34681
+ },
34682
+ onRemove: function (m) { m.off('click', close); if (el && el.parentNode) { el.parentNode.removeChild(el); } el = null; },
34683
+ };
34684
+ }
34685
+
31308
34686
  // ------------------------------------------------------------------ plan editor (OPEN-ROUTE-EDIT E10)
31309
34687
 
31310
34688
  /**
@@ -31824,7 +35202,9 @@ function smapCreateSdk(engine, interop, plan) {
31824
35202
  var out = { type: 'smap.layers', version: 1 };
31825
35203
  if (!this._customStyle) { out.basemap = { style: this._serverStyle || this._flavor, language: this._language, overrides: clone(this._basemapOverrides) }; }
31826
35204
  if (this._sourceOrder.length) { out.sources = this.sources(); }
31827
- out.layers = this._order.map(function (id) {
35205
+ // The shared description has points, lines, areas and style layers; custom markers, heat maps and 3D models are
35206
+ // not part of it and are left out.
35207
+ out.layers = this._order.filter(function (id) { return ['points', 'lines', 'polygons', 'style'].indexOf(self._layers[id].kind) >= 0; }).map(function (id) {
31828
35208
  var def = self._layers[id];
31829
35209
  var e = { id: id, kind: def.kind };
31830
35210
  if (def.slot) { e.slot = def.slot; }
@@ -31883,7 +35263,8 @@ function smapCreateSdk(engine, interop, plan) {
31883
35263
  def.slot = o.slot || null;
31884
35264
  def.before = o.before || null;
31885
35265
  def.popupFn = typeof o.popup === 'string' ? popupTemplate(o.popup) : null;
31886
- def.zIndex = def.o.zIndex || 0;
35266
+ // A layer's place among layers; a per-feature zIndex (custom markers) orders within the layer only.
35267
+ def.zIndex = typeof def.o.zIndex === 'number' ? def.o.zIndex : 0;
31887
35268
  def.engineLayers = [];
31888
35269
  if (this._layerToolHides(id)) { def.hidden = true; }
31889
35270
  this._layers[id] = def;
@@ -31942,6 +35323,10 @@ function smapCreateSdk(engine, interop, plan) {
31942
35323
 
31943
35324
  SMap.prototype._drop = function (id, def) {
31944
35325
  var m = this.engine;
35326
+ if (def.kind === 'custom') { this._dropCustom(id, def); return; }
35327
+ if (this._ghost && this._ghost.id === id && m) { this._dropGhost(id); }
35328
+ if (this._tooltipFor && this._tooltipFor.id === id) { this._hideTooltip(); }
35329
+ if (def.clusterSet) { this._dropCustom(id + ':clusters', def.clusterSet); def.clusterSet = null; }
31945
35330
  if (!m) { return; }
31946
35331
  def.engineLayers.forEach(function (l) { if (m.getLayer(l)) { m.removeLayer(l); } });
31947
35332
  if (def.kind !== 'style' && m.getSource('smap-' + id)) { m.removeSource('smap-' + id); }
@@ -31961,13 +35346,24 @@ function smapCreateSdk(engine, interop, plan) {
31961
35346
  Object.keys(this._basemapEdits).forEach(function (id) { self._applyEdits(id, self._basemapEdits[id]); });
31962
35347
  this._sourceOrder.forEach(function (id) { if (!m.getSource(id)) { self._engineSource(id); } });
31963
35348
  this._applyBuildings();
35349
+ this._imageryHid = [];
35350
+ if (this._baseImagery) { this._applyBaseImagery(); }
35351
+ if (this._terrain) { this._applyTerrain(); }
31964
35352
  this._order.forEach(function (id) { self._add(id, self._layers[id]); });
31965
35353
  };
31966
35354
 
31967
35355
  SMap.prototype._add = function (id, def) {
31968
35356
  var m = this.engine;
31969
35357
  var o = def.o;
35358
+ if (def.kind === 'custom') { this._addCustom(id, def); return; }
31970
35359
  var before = this._beforeId(id);
35360
+ if (def.kind === 'models') {
35361
+ var modelLayer = this._modelLayer(id, def);
35362
+ if (o.minzoom !== undefined) { modelLayer.minzoom = o.minzoom; }
35363
+ m.addLayer(modelLayer, before);
35364
+ def.engineLayers.push(modelLayer.id);
35365
+ return;
35366
+ }
31971
35367
  if (def.kind === 'style') {
31972
35368
  // Passed to the engine as it is (a copy, so the engine never holds the object you gave).
31973
35369
  var styleLayer = clone(def.layer);
@@ -31983,6 +35379,8 @@ function smapCreateSdk(engine, interop, plan) {
31983
35379
  if (o.maxzoom !== undefined) { range.maxzoom = o.maxzoom; }
31984
35380
  var visibility = def.hidden ? 'none' : 'visible';
31985
35381
  var source = { type: 'geojson', data: def.data, promoteId: o.idProperty };
35382
+ // A dragged point is found again by its place in the data (unless idProperty names it).
35383
+ if (def.kind === 'points' && o.draggable && !o.idProperty) { source.generateId = true; }
31986
35384
  if (def.kind === 'points' && o.cluster) {
31987
35385
  source.cluster = true;
31988
35386
  source.clusterRadius = (o.cluster && o.cluster.radius) || 50;
@@ -32005,7 +35403,8 @@ function smapCreateSdk(engine, interop, plan) {
32005
35403
  var color = o.color || '#4f46e5';
32006
35404
  var main;
32007
35405
  if (def.kind === 'points') {
32008
- if (o.cluster) {
35406
+ var htmlClusters = o.cluster && (o.cluster.html || o.cluster.ring);
35407
+ if (o.cluster && !htmlClusters) {
32009
35408
  add({
32010
35409
  id: src + '-clusters', type: 'circle', filter: ['has', 'point_count'],
32011
35410
  paint: {
@@ -32026,6 +35425,7 @@ function smapCreateSdk(engine, interop, plan) {
32026
35425
  });
32027
35426
  });
32028
35427
  }
35428
+ if (htmlClusters) { this._htmlClusters(id, def, src); }
32029
35429
  var only = o.cluster ? ['!', ['has', 'point_count']] : undefined;
32030
35430
  var both = function (extra) { return only ? ['all', only, extra] : extra; };
32031
35431
  if (o.marker) {
@@ -32120,6 +35520,30 @@ function smapCreateSdk(engine, interop, plan) {
32120
35520
  paint: { 'text-color': '#1f2937', 'text-halo-color': '#ffffff', 'text-halo-width': 1.4 },
32121
35521
  });
32122
35522
  }
35523
+ } else if (def.kind === 'heatmap') {
35524
+ main = src + '-heat';
35525
+ var hc = o.colors;
35526
+ var ramp = Array.isArray(hc) && hc.length && Array.isArray(hc[0]) ? hc : null;
35527
+ var colorExpr = ['interpolate', ['linear'], ['heatmap-density']];
35528
+ if (ramp) { ramp.forEach(function (st) { colorExpr.push(st[0], st[1]); }); }
35529
+ else if (Array.isArray(hc) && hc.length) {
35530
+ // Colours from low to high: transparent at no density, then evenly spaced.
35531
+ colorExpr.push(0, 'rgba(0, 0, 0, 0)');
35532
+ hc.forEach(function (c, i) { colorExpr.push((i + 1) / hc.length, c); });
35533
+ } else {
35534
+ 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)');
35535
+ }
35536
+ var weight = o.weight === undefined ? 1 : (typeof o.weight === 'number' ? o.weight : ['to-number', valueExpr(o.weight, 1), 1]);
35537
+ add({
35538
+ id: main, type: 'heatmap',
35539
+ paint: {
35540
+ 'heatmap-weight': weight,
35541
+ 'heatmap-radius': o.radius === undefined ? 20 : o.radius,
35542
+ 'heatmap-intensity': o.intensity === undefined ? 1 : o.intensity,
35543
+ 'heatmap-opacity': o.opacity === undefined ? 0.8 : o.opacity,
35544
+ 'heatmap-color': colorExpr,
35545
+ },
35546
+ });
32123
35547
  } else if (def.kind === 'lines') {
32124
35548
  main = src + '-lines';
32125
35549
  // simplestyle (stroke, stroke-width, stroke-opacity) when the layer gives no colour of its own
@@ -32144,6 +35568,15 @@ function smapCreateSdk(engine, interop, plan) {
32144
35568
  };
32145
35569
  if (o.dash) { paint['line-dasharray'] = o.dash; }
32146
35570
  add({ id: main, type: 'line', layout: round, paint: paint });
35571
+ if (o.label) {
35572
+ // A permanent label along the line (a route's name), repeated along long lines.
35573
+ add({
35574
+ id: src + '-labels', type: 'symbol',
35575
+ layout: { 'symbol-placement': 'line', 'symbol-spacing': o.labelSpacing || 250, 'text-field': ['to-string', ['get', o.label]],
35576
+ 'text-font': ['Noto Sans Medium'], 'text-size': 12, 'text-keep-upright': true },
35577
+ paint: { 'text-color': valueExpr(o.labelColor, '#1f2937'), 'text-halo-color': '#ffffff', 'text-halo-width': 1.6 },
35578
+ });
35579
+ }
32147
35580
  if (o.arrows) {
32148
35581
  var ar = o.arrows === true ? {} : o.arrows;
32149
35582
  var arrowSize = ar.size || 14;
@@ -32186,7 +35619,9 @@ function smapCreateSdk(engine, interop, plan) {
32186
35619
  }
32187
35620
  // The popup is opened by the map's one click handler (_popupClick), from this layer's own hit test.
32188
35621
  def.popupLayer = o.popup ? main : null;
32189
- if (main && (o.popup || o.onClick)) {
35622
+ if (main && o.tooltip) { this._tooltips(id, def, main); }
35623
+ if (main && def.kind === 'points' && o.draggable) { this._dragPoints(id, def, main); }
35624
+ if (main && (o.popup || o.onClick || o.draggable)) {
32190
35625
  if (o.onClick) {
32191
35626
  this._listen(id, 'click', main, function (e) { o.onClick(e.features[0], e); });
32192
35627
  }
@@ -32257,6 +35692,8 @@ function smapCreateSdk(engine, interop, plan) {
32257
35692
  slots: SLOTS.slice(),
32258
35693
  formats: interop.formats,
32259
35694
  convert: interop.convert,
35695
+ geo: interop.geo,
35696
+ useThree: interop.useThree,
32260
35697
  rasterUrl: interop.rasterUrl,
32261
35698
  rasterTileJsonUrl: interop.rasterTileJsonUrl,
32262
35699
  styleUrl: interop.styleUrl,
@@ -32274,5 +35711,5 @@ function smapCreateSdk(engine, interop, plan) {
32274
35711
 
32275
35712
  return module.exports;
32276
35713
  }
32277
- (typeof globalThis !== 'undefined' ? globalThis : window).sMap = smapCreateSdk(smapCreateEngine(), smapCreateInterop(), smapCreatePlan());
35714
+ (typeof globalThis !== 'undefined' ? globalThis : window).sMap = smapCreateSdk(smapCreateEngine(), smapCreateInterop(), smapCreateCanvas(), smapCreatePlan());
32278
35715
  })();