-
Notifications
You must be signed in to change notification settings - Fork 16
Expand file tree
/
Copy pathWMECitiesOverlay.js
More file actions
1775 lines (1633 loc) · 70.6 KB
/
Copy pathWMECitiesOverlay.js
File metadata and controls
1775 lines (1633 loc) · 70.6 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
// ==UserScript==
// @name WME Cities Overlay
// @namespace https://greasyfork.org/en/users/166843-wazedev
// @version 2026.03.08.00
// @description Adds a city overlay for selected states
// @author WazeDev
// @match https://www.waze.com/*/editor*
// @match https://www.waze.com/editor*
// @match https://beta.waze.com/*
// @exclude https://www.waze.com/*user/*editor/*
// @require https://cdn.jsdelivr.net/npm/@turf/turf@7/turf.min.js
// @require https://greasyfork.org/scripts/24851-wazewrap/code/WazeWrap.js
// @require https://update.greasyfork.org/scripts/546306/1644332/WME%20Cities%20Overlay_DB.js
// @require https://update.greasyfork.org/scripts/524747/1542062/GeoKMLer.js
// @license GNU GPLv3
// @grant GM_xmlhttpRequest
// @connect api.github.com
// @connect raw.githubusercontent.com
// @contributionURL https://github.com/WazeDev/Thank-The-Authors
// ==/UserScript==
/* ecmaVersion 2017 */
/* global $ */
/* global idbKeyval */
/* global turf */
/* global WazeWrap */
/* global I18n */
/* eslint curly: ["warn", "multi-or-nest"] */
(function () {
'use strict';
const debug = false;
const scriptMetadata = GM_info.script;
const scriptName = scriptMetadata.name;
const repoOwner = scriptMetadata.author; // Change this to a different repo username when testing a forked branch!
const _settingsStoreName = '_wme_cities';
let _settings;
let _kml; // Holds the raw input KML File data
let _layer = null; // Holds the geoJSON converted features to map with the SDK
const layerid = scriptName.replace(/[^a-z0-9_-]/gi, '_');
const labelsLayerId = `${layerid}_labels`;
// Default style constants (used only as defaults in loadSettings)
const _defaultStrokeColor = '#E6E6E6';
const _defaultFillColor = '#E6E6E6';
const _defaultFillOpacity = 0.2;
const _defaultStrokeOpacity = 0.6;
const _defaultLabelColor = '#ffffff';
const _defaultLabelOutlineColor = '#000000';
const _defaultLabelFontSize = 12;
const _defaultLabelOutlineWidth = 2;
const _defaultHighlightColor = '#f7ad25';
let currState = '';
let currCity = [];
let kmlCache = {};
// Screen polygon cache — rebuilt only when the map extent changes
let _cachedExtent = null;
let _cachedScreenPolygon = null;
let _cachedScreenArea = null;
loadSettings();
const _US_States = {
Alabama: 'AL',
Alaska: 'AK',
Arizona: 'AZ',
Arkansas: 'AR',
California: 'CA',
Colorado: 'CO',
Connecticut: 'CT',
'District of Columbia': 'DC',
Delaware: 'DE',
Florida: 'FL',
Georgia: 'GA',
Hawaii: 'HI',
Idaho: 'ID',
Illinois: 'IL',
Indiana: 'IN',
Iowa: 'IA',
Kansas: 'KS',
Kentucky: 'KY',
Louisiana: 'LA',
Maine: 'ME',
Maryland: 'MD',
Massachusetts: 'MA',
Michigan: 'MI',
Minnesota: 'MN',
Mississippi: 'MS',
Missouri: 'MO',
Montana: 'MT',
Nebraska: 'NE',
Nevada: 'NV',
'New Hampshire': 'NH',
'New Jersey': 'NJ',
'New Mexico': 'NM',
'New York': 'NY',
'North Carolina': 'NC',
'North Dakota': 'ND',
Ohio: 'OH',
Oklahoma: 'OK',
Oregon: 'OR',
Pennsylvania: 'PA',
'Rhode Island': 'RI',
'South Carolina': 'SC',
'South Dakota': 'SD',
Tennessee: 'TN',
Texas: 'TX',
Utah: 'UT',
Vermont: 'VT',
Virginia: 'VA',
Washington: 'WA',
'West Virginia': 'WV',
Wisconsin: 'WI',
Wyoming: 'WY',
getAbbreviation: function (state) {
return this[state];
},
getStateFromAbbr: function (abbr) {
return Object.entries(_US_States).filter((x) => {
if (x[1] == abbr) return x;
})[0][0];
},
getStatesArray: function () {
return Object.keys(_US_States).filter((x) => {
if (typeof _US_States[x] !== 'function') return x;
});
},
getStateAbbrArray: function () {
return Object.values(_US_States).filter((x) => {
if (typeof x !== 'function') return x;
});
},
};
const _MX_States = {
Aguascalientes: 'AGS',
'Baja California': 'BC',
'Baja California Sur': 'BCS',
Campeche: 'CAM',
'Coahuila de Zaragoza': 'COAH',
Colima: 'COL',
Chiapas: 'CHIS',
Durango: 'DGO',
'Ciudad de México': 'CDMX',
Guanajuato: 'GTO',
Guerrero: 'GRO',
Hidalgo: 'HGO',
Jalisco: 'JAL',
'Estado de México': 'EM',
'Michoacán de Ocampo': 'MICH',
Morelos: 'MOR',
Nayarit: 'NAY',
'Nuevo León': 'NL',
Oaxaca: 'OAX',
Puebla: 'PUE',
'Quintana Roo': 'QROO',
Querétaro: 'QRO',
'San Luis Potosí': 'SLP',
Sinaloa: 'SIN',
Sonora: 'SON',
Tabasco: 'TAB',
Tamaulipas: 'TAM',
Tlaxcala: 'TLAX',
'Veracruz Ignacio de la Llave': 'VER',
Yucatán: 'YUC',
Zacatecas: 'ZAC',
getAbbreviation: function (state) {
return this[state];
},
getStateFromAbbr: function (abbr) {
return Object.entries(_MX_States).filter((x) => {
if (x[1] == abbr) return x;
})[0][0];
},
getStatesArray: function () {
return Object.keys(_MX_States).filter((x) => {
if (typeof _MX_States[x] !== 'function') return x;
});
},
getStateAbbrArray: function () {
return Object.values(_MX_States).filter((x) => {
if (typeof x !== 'function') return x;
});
},
};
const _CA_States = {
Alberta: 'AB',
'British Columbia': 'BC',
Manitoba: 'MB',
'New Brunswick': 'NB',
'Newfoundland and Labrador': 'NL',
'Nova Scotia': 'NS',
Nunavut: 'NT',
'Northwest Territories': 'NU',
Ontario: 'ON',
'Prince Edward Island': 'PE',
Quebec: 'QC',
Saskatchewan: 'SK',
Yukon: 'YT',
getAbbreviation: function (state) {
return this[state];
},
getStateFromAbbr: function (abbr) {
return Object.entries(_CA_States).filter((x) => {
if (x[1] == abbr) return x;
})[0][0];
},
getStatesArray: function () {
return Object.keys(_CA_States).filter((x) => {
if (typeof _CA_States[x] !== 'function') return x;
});
},
getStateAbbrArray: function () {
return Object.values(_CA_States).filter((x) => {
if (typeof x !== 'function') return x;
});
},
};
let wmeSDK; // Declare wmeSDK globally
// Ensure SDK_INITIALIZED is available
if (unsafeWindow.SDK_INITIALIZED) {
unsafeWindow.SDK_INITIALIZED.then(bootstrap).catch((err) => {
console.error(`${scriptName}: SDK initialization failed`, err);
});
} else {
console.warn(`${scriptName}: SDK_INITIALIZED is undefined`);
}
/**
* Acquires the WME SDK instance and waits for all three dependencies (WME, WazeWrap,
* GeoKMLer) to become ready in parallel before calling `init()`.
*/
function bootstrap() {
wmeSDK = unsafeWindow.getWmeSdk({
scriptId: scriptName.replaceAll(' ', ''),
scriptName: scriptName,
});
// Use Promise.all to check readiness of all dependencies
Promise.all([isWmeReady(), isWazeWrapReady(), isGeoKMLerReady()])
.then(() => {
console.log(`${scriptName}: All dependencies are ready.`);
init();
console.log(`${scriptName}: Initialized`);
})
.catch((error) => {
console.error(`${scriptName}: Error during bootstrap -`, error);
});
}
/**
* Returns a Promise that resolves when the WME SDK and all required SDK sub-modules
* (Sidebar, LayerSwitcher, Shortcuts, Events) are fully loaded and ready.
*
* @returns {Promise<void>}
*/
function isWmeReady() {
return new Promise((resolve, reject) => {
if (wmeSDK && wmeSDK.State.isReady() && wmeSDK.Sidebar && wmeSDK.LayerSwitcher && wmeSDK.Shortcuts && wmeSDK.Events) {
console.log(`${scriptName}: WME is already ready.`);
resolve();
} else {
wmeSDK.Events.once({ eventName: 'wme-ready' })
.then(() => {
if (wmeSDK.Sidebar && wmeSDK.LayerSwitcher && wmeSDK.Shortcuts && wmeSDK.Events) {
console.log(`${scriptName}: WME is fully ready now.`);
resolve();
} else {
reject(`${scriptName}: Some SDK components are not loaded.`);
}
})
.catch((error) => {
console.error(`${scriptName}: Error while waiting for WME to be ready:`, error);
reject(error);
});
}
});
}
/**
* Returns a Promise that resolves when the global `WazeWrap.Ready` flag is set.
* Polls every 500 ms for up to 1000 attempts before rejecting on timeout.
*
* @returns {Promise<void>}
*/
function isWazeWrapReady() {
return new Promise((resolve, reject) => {
const maxTries = 1000;
const checkInterval = 500;
(function check(tries = 0) {
if (unsafeWindow.WazeWrap && unsafeWindow.WazeWrap.Ready) {
console.log(`${scriptName}: WazeWrap is successfully loaded.`);
resolve();
} else if (tries < maxTries) {
setTimeout(() => check(++tries), checkInterval);
} else {
reject(`${scriptName}: WazeWrap took too long to load.`);
}
})();
});
}
/**
* Returns a Promise that resolves when the globally injected `GeoKMLer` class is defined
* and can be successfully instantiated.
*
* @returns {Promise<void>}
*/
function isGeoKMLerReady() {
return new Promise((resolve, reject) => {
try {
if (typeof GeoKMLer !== 'undefined') {
const geoKMLer = new GeoKMLer();
if (geoKMLer) {
console.log(`${scriptName}: GeoKMLer is successfully loaded and ready.`);
resolve();
} else {
reject(`${scriptName}: GeoKMLer instance could not be created.`);
}
} else {
reject(`${scriptName}: GeoKMLer is not defined.`);
}
} catch (error) {
console.error(`${scriptName}: Error during GeoKMLer readiness check:`, error);
reject(error);
}
});
}
/**
* Loads persisted settings from localStorage into `_settings`, merging any missing
* keys with their default values so the settings object is always fully populated.
*/
function loadSettings() {
_settings = $.parseJSON(localStorage.getItem(_settingsStoreName));
const defaults = {
layerVisible: true,
ShowCityLabels: true,
FillPolygons: true,
HighlightFocusedCity: true,
AutoUpdateKMLs: true,
strokeColor: _defaultStrokeColor,
fillColor: _defaultFillColor,
strokeOpacity: _defaultStrokeOpacity,
fillOpacity: _defaultFillOpacity,
labelColor: _defaultLabelColor,
labelColorMatchStroke: false,
labelOutlineColor: _defaultLabelOutlineColor,
labelOutlineColorMatchStroke: false,
labelFontSize: _defaultLabelFontSize,
labelFontSizeRelative: true,
labelOutlineWidth: _defaultLabelOutlineWidth,
labelOutlineWidthRelative: true,
highlightColor: _defaultHighlightColor,
};
if (!_settings) _settings = defaults;
for (const prop in defaults) {
if (!Object.prototype.hasOwnProperty.call(_settings, prop)) _settings[prop] = defaults[prop];
}
}
/**
* Persists the current `_settings` values to localStorage as a JSON string.
*/
function saveSettings() {
if (localStorage) {
const settings = {
layerVisible: _settings.layerVisible,
ShowCityLabels: _settings.ShowCityLabels,
FillPolygons: _settings.FillPolygons,
HighlightFocusedCity: _settings.HighlightFocusedCity,
AutoUpdateKMLs: _settings.AutoUpdateKMLs,
strokeColor: _settings.strokeColor,
fillColor: _settings.fillColor,
strokeOpacity: _settings.strokeOpacity,
fillOpacity: _settings.fillOpacity,
labelColor: _settings.labelColor,
labelColorMatchStroke: _settings.labelColorMatchStroke,
labelOutlineColor: _settings.labelOutlineColor,
labelOutlineColorMatchStroke: _settings.labelOutlineColorMatchStroke,
labelFontSize: _settings.labelFontSize,
labelFontSizeRelative: _settings.labelFontSizeRelative,
labelOutlineWidth: _settings.labelOutlineWidth,
labelOutlineWidthRelative: _settings.labelOutlineWidthRelative,
};
localStorage.setItem(_settingsStoreName, JSON.stringify(settings));
}
}
/**
* Recursively removes the third (elevation/Z) value from a GeoJSON coordinate array,
* normalising all geometries to 2D [longitude, latitude] pairs.
*
* @param {Array} coordinates - A coordinate array at any nesting depth.
* @returns {Array} The same structure with every leaf coordinate truncated to [x, y].
*/
function stripElevation(coordinates) {
if (Array.isArray(coordinates[0])) {
// If coordinates are nested, recursively strip elevation
return coordinates.map((coord) => stripElevation(coord));
}
// Remove third element from a single set of coordinates
return coordinates.slice(0, 2);
}
/**
* Converts a GeoJSON FeatureCollection into a flat array of simple-geometry Features.
* Multi-geometry types (MultiPolygon, MultiLineString, MultiPoint) and GeometryCollections
* are decomposed into individual Features via `turf.flattenEach`. Each feature's name
* property is cleaned of KML artefact characters and copied to `properties.labelText`.
* All coordinates are stripped to 2D using `stripElevation`.
*
* @param {Object} geoJson - A GeoJSON FeatureCollection.
* @returns {Array<Object>} Flat array of GeoJSON Feature objects ready for layer use.
* @throws {Error} If `geoJson` is not a valid FeatureCollection.
*/
function flattenGeoJSON(geoJson) {
if (geoJson.type !== 'FeatureCollection' || !Array.isArray(geoJson.features)) {
throw new Error('Invalid GeoJSON input: expected a FeatureCollection.');
}
const result = [];
turf.flattenEach(geoJson, (feature) => {
if (feature.properties) {
const nameKey = ['name', 'Name', 'NAME'].find((k) => feature.properties[k]);
if (nameKey) {
feature.properties[nameKey] = feature.properties[nameKey]
.replace(/<at><openparen>/gi, '')
.replace(/<closeparen>/gi, '');
feature.properties.labelText = feature.properties[nameKey];
}
}
result.push({
type: 'Feature',
geometry: {
type: feature.geometry.type,
coordinates: stripElevation(feature.geometry.coordinates),
},
properties: feature.properties,
});
});
return result;
}
/**
* Parses a KML string into a flat array of GeoJSON Features using the GeoKMLer library
* followed by `flattenGeoJSON` to normalise and decompose the result.
*
* @param {string} strKML - Raw KML document string.
* @returns {Array<Object>} Flat array of GeoJSON Feature objects.
*/
function GetFeaturesFromKMLString(strKML) {
const geoKMLer = new GeoKMLer();
const kmlDoc = geoKMLer.read(strKML);
const GeoJSONflat = flattenGeoJSON(geoKMLer.toGeoJSON(kmlDoc, false)); // false = don't need the added CRS info section
return GeoJSONflat;
}
/**
* Function: findCurrCity
* ----------------------
* Determines the current city based on the map's center point, identifying its feature
* within GeoJSON layers, and handling DOM element retrieval for the current feature.
*
* Steps:
* 1. Initialize the `cityData` object with default properties.
* 2. Retrieve the current map center coordinates using `wmeSDK.Map`.
* 3. Iterate over all features in the global `_layer` array to check if the map center is
* within any polygon feature using `isPointInPolygon`.
* - If a match is found, update `cityData` with the feature's details.
* 4. Perform a debug-only operation to find the DOM element associated with the feature:
* - Retrieve using `wmeSDK.Map.getFeatureDomElement` if the `featureId` is valid.
* - Handle cases where the DOM element is not found or retrieval errors occur.
* 5. Log the finalized `cityData` object for debugging purposes.
*
* Globals:
* - `scriptName`: Used for logging errors and debug information.
* - `_layer`: Array of GeoJSON features representing map polygons and properties.
* - `debug`: Flag to enable additional logging for troubleshooting.
* - `layerid`: Identifier for the map layer, needed for DOM element retrieval.
*
* Error Handling and Debugging:
* - Includes additional logging and checks to address missing elements and potential errors.
* - Detailed console warnings and errors facilitate debugging when `debug` mode is activated.
*
* Returns:
* - `cityData`: An object containing the current city's name, associated feature ID, and optional DOM element.
*/
function findCurrCity() {
let cityData = {
name: '',
featureId: '',
domElement: null, // Initialize as null for safety
};
// Get the current map center using wmeSDK
const mapCenter = wmeSDK.Map.getMapCenter(); // Returns { lat: number, lon: number }
const mapCenterPoint = [mapCenter.lon, mapCenter.lat];
// Check if _layer is defined and not null before proceeding
if (!_layer || !_layer.length) {
if (debug) console.warn(`${scriptName}: _layer is null or undefined. Unable to find current city.`);
return cityData;
}
for (let i = 0; i < _layer.length; i++) {
const feature = _layer[i];
const properties = feature.properties;
const id = feature.id;
// Check if the map center point is inside the feature's geometry (polygon)
if (turf.booleanPointInPolygon(turf.point(mapCenterPoint), feature)) {
cityData.name = properties.name;
cityData.featureId = id;
if (debug) {
cityData.geojson = feature;
}
break;
}
}
if (debug) {
// Only attempt to get the DOM element if a valid featureId has been set
if (cityData.featureId) {
try {
const currCityFeatureDomElement = wmeSDK.Map.getFeatureDomElement({
featureId: cityData.featureId,
layerName: layerid,
});
if (currCityFeatureDomElement !== null) {
cityData.domElement = currCityFeatureDomElement;
} else {
console.warn(`${scriptName}: DOM element for feature ID ${cityData.featureId} not found.`);
}
} catch (error) {
console.error(`${scriptName}: Error retrieving DOM element for feature ID ${cityData.featureId}:`, error);
}
}
}
if (debug) {
console.log(`${scriptName}: Current Focused City Object is:`, cityData);
}
return cityData;
}
/**
* Function: updateCitiesLayer
* ---------------------------
* Asynchronously updates the cities layer on the map based on the current state and zoom level,
* ensuring proper display of city polygons and region names.
*
* Steps:
* 1. Check the map's current zoom level and exit early if it's below 12, as detailed city view is unnecessary.
* 2. Retrieve the top state from the map data model. If different from the current state (`currState`),
* invoke `updateCityPolygons` to refresh city polygon data.
* 3. Identify the current city using `findCurrCity`. Ensure the city data is valid before proceeding.
* 4. Update the display name of the district or region using `updateDistrictNameDisplay`.
* 5. Redraw the map layer to reflect the updated city data.
*
* Error Handling:
* - Try-catch block used to handle any runtime errors gracefully, logging details for debugging.
* - Checks for valid `currCity` and `currCity.name` to prevent operations on missing data.
*
* Globals:
* - `scriptName`: Used for logging errors and operation details.
* - `currState`: Tracks the name of the state currently being processed.
* - `layerid`: Identifier for the target layer where cities are displayed.
* - `currCity`: Object to store the currently identified city, utilized in display logic.
*/
async function updateCitiesLayer() {
try {
const zoom = wmeSDK.Map.getZoomLevel();
if (zoom < 5) {
return;
}
const topState = wmeSDK.DataModel.States.getTopState();
if (!topState) {
if (debug) console.log(`${scriptName}: topState is null. Skipping updateCityPolygons.`);
return;
}
if (currState !== topState.name) {
await updateCityPolygons(); // loads polygons + calls refreshLabels internally
} else {
refreshLabels(); // same state — recompute labels for new viewport
}
currCity = findCurrCity();
if (!currCity || !currCity.name) {
if (debug) console.log(`${scriptName}: No Current city Polygon found for this location....`);
return;
}
updateDistrictNameDisplay();
wmeSDK.Map.redrawLayer({ layerName: layerid });
} catch (error) {
console.error(`${scriptName}: Error in updateCitiesLayer -`, error);
}
}
/**
* Creates or refreshes the cyan city-name label injected into the WME
* location-info bar. Removes any existing label first, then appends a new one
* only when `_layer` has features and `currCity.name` is set.
*/
function updateDistrictNameDisplay() {
// Remove existing district name displays
$('.wmecitiesoverlay-region').remove();
// Verify if _layer has features and a current city is specified
if (Array.isArray(_layer) && _layer.length > 0 && currCity.name != '') {
let color = '#00ffff';
// Create a new div element for displaying the current city
var $div = $('<div>', {
id: 'wmecitiesoverlay',
class: 'wmecitiesoverlay-region',
style: 'float:left; margin-left:10px;',
}).css({
color: color,
cursor: 'pointer',
});
var $span = $('<span>').css({ display: 'inline-block' });
$span.text(currCity.name).appendTo($div);
// Append the new element after the location-info-region
$('.location-info-region').after($div);
}
}
/**
* Clears all features from the polygon layer and re-adds the current `_layer` array,
* ensuring the map reflects the latest loaded city boundaries.
*/
function addPolygonsToLayer() {
if (!_layer || !_layer.length) return;
wmeSDK.Map.removeAllFeaturesFromLayer({ layerName: layerid });
wmeSDK.Map.dangerouslyAddFeaturesToLayerWithoutValidation({
features: _layer,
layerName: layerid,
});
}
/**
* Rebuilds the label layer for the current viewport. Clears existing label features,
* then for each city polygon that passes a fast bounding-box pre-filter, calls
* `getLabelPoints` to compute intersection-based label positions and adds them to the
* labels layer. Does nothing if labels are disabled or `_layer` is empty.
*/
function refreshLabels() {
wmeSDK.Map.removeAllFeaturesFromLayer({ layerName: labelsLayerId });
if (!_settings.ShowCityLabels || !_layer || !_layer.length) return;
const ext = wmeSDK.Map.getMapExtent(); // [minX, minY, maxX, maxY]
const allLabels = [];
_layer.forEach((feature) => {
// Fast bbox pre-filter — skip turf.intersect for off-screen polygons
const b = feature.properties._bbox;
if (!b || b[0] > ext[2] || b[2] < ext[0] || b[1] > ext[3] || b[3] < ext[1]) return;
const points = getLabelPoints(feature);
if (points.length) allLabels.push(...points);
});
if (allLabels.length) {
wmeSDK.Map.dangerouslyAddFeaturesToLayerWithoutValidation({
features: allLabels,
layerName: labelsLayerId,
});
}
}
/**
* Computes label point Features for a single city polygon by intersecting it with
* the current screen viewport. Each intersection fragment larger than 0.5% of the
* screen area gets a label placed at its center-of-mass (or `pointOnFeature` as a
* fallback when the centroid falls outside the polygon).
*
* @param {Object} feature - A GeoJSON Feature with a Polygon geometry.
* @returns {Array<Object>} Array of GeoJSON Point Features (may be empty).
*/
function getLabelPoints(feature) {
const screenPolygon = getScreenPolygon();
const intersection = turf.intersect(turf.featureCollection([screenPolygon, feature]));
const polygons = [];
if (intersection) {
switch (intersection.geometry.type) {
case 'Polygon':
polygons.push(intersection);
break;
case 'MultiPolygon':
intersection.geometry.coordinates.forEach((ring) => polygons.push(turf.polygon(ring)));
break;
default:
break;
}
}
const screenArea = getScreenArea();
return polygons
.filter((polygon) => {
const polygonArea = turf.area(polygon);
return polygonArea / screenArea > 0.005;
})
.map((polygon) => {
let point = turf.centerOfMass(polygon);
if (!turf.booleanPointInPolygon(point, polygon)) {
point = turf.pointOnFeature(polygon);
}
point.properties = { type: 'label', labelText: feature.properties.labelText };
point.id = 0;
return point;
});
}
/**
* Lazily rebuilds the screen-polygon and screen-area caches whenever the map extent
* changes. Called by `getScreenPolygon` and `getScreenArea` before returning their
* cached values, so callers always receive an up-to-date result without performing
* redundant recalculations on each label refresh.
*/
function ensurePolygonCaches() {
const ext = wmeSDK.Map.getMapExtent();
if (
_cachedExtent &&
_cachedScreenPolygon &&
_cachedScreenArea !== null &&
_cachedExtent[0] === ext[0] &&
_cachedExtent[1] === ext[1] &&
_cachedExtent[2] === ext[2] &&
_cachedExtent[3] === ext[3]
) {
return;
}
_cachedExtent = ext;
_cachedScreenPolygon = turf.polygon([
[
[ext[0], ext[3]],
[ext[2], ext[3]],
[ext[2], ext[1]],
[ext[0], ext[1]],
[ext[0], ext[3]],
],
]);
_cachedScreenArea = turf.area(_cachedScreenPolygon);
}
/**
* Returns the current viewport as a turf Polygon Feature, updating the cache first
* if the map extent has changed since the last call.
*
* @returns {Object} A turf Polygon Feature representing the visible map extent.
*/
function getScreenPolygon() {
ensurePolygonCaches();
return _cachedScreenPolygon;
}
/**
* Returns the area of the current viewport in square metres, updating the cache first
* if the map extent has changed since the last call.
*
* @returns {number} Viewport area in m².
*/
function getScreenArea() {
ensurePolygonCaches();
return _cachedScreenArea;
}
/**
* Performs a GET request via the Tampermonkey `GM_xmlhttpRequest` API, bypassing
* browser CORS restrictions for cross-origin GitHub raw-content URLs.
*
* @param {string} url - The URL to fetch.
* @returns {Promise<string>} Resolves with the response text, or rejects on HTTP 4xx/5xx
* or network error.
*/
async function fetch(url) {
//return await $.get(url);
return new Promise((resolve, reject) => {
GM_xmlhttpRequest({
url: url,
method: 'GET',
onload(res) {
if (res.status < 400) {
resolve(res.responseText);
} else {
reject(res);
}
},
onerror(res) {
reject(res);
},
});
});
}
/**
* Function: updateAllMaps
* -----------------------
* Asynchronously updates KML data for all states in the current country, comparing
* local storage against the latest content available in a GitHub repository.
*
* Steps:
* 1. Get the top country from the map data model and retrieve its abbreviation.
* 2. Fetch the keys for all states' city data stored locally.
* 3. Determine the appropriate state abbreviation object based on the country's abbreviation.
* 4. Retrieve the list of KML files from the GitHub repository, parsing the response.
* 5. For each state in local storage, check if the KML file size differs from the server's version.
* If so, fetch the updated KML file, update local storage, and cache if necessary.
* 6. Log the count and names of states updated in the user's interface.
* 7. Finally, refresh city layers using `updateCitiesLayer`.
*
* Note:
* - Utilizes persistent local storage (`idbKeyval`) and caching (`kmlCache`) to reduce unnecessary data loads.
* - Updates DOM element `#WMECOupdateStatus` to reflect operation results, aiding user interaction and feedback.
*
* Globals:
* - `scriptName`: The name used for logging and user feedback.
* - `repoOwner`: Identifier for the GitHub repository owner, used for URL generation.
* - `currState`: Tracks the current state being processed, updated during KML fetching.
* - `_kml`: Stores KML data when a matching state is currently active.
* - `layerid`: Identifier for the map layer where updates are applied.
* - `_US_States` and `_MX_States`: Objects managing state abbreviation lookup.
* - `kmlCache`: Object to locally cache loaded KML data for efficient retrieval.
*/
async function updateAllMaps() {
const topCountry = wmeSDK.DataModel.Countries.getTopCountry();
let countryAbbr = topCountry.abbr;
let keys = await idbKeyval.keys(`${countryAbbr}_states_cities`);
let updatedCount = 0;
let updatedStates = '';
let countryAbbrObj;
if (countryAbbr === 'US') countryAbbrObj = _US_States;
else if (countryAbbr === 'MX') countryAbbrObj = _MX_States;
else if (countryAbbr === 'CA') countryAbbrObj = _CA_States;
let KMLinfoArr = await fetch(`https://api.github.com/repos/${repoOwner}/WME-Cities-Overlay/contents/KMLs/${countryAbbr}`);
KMLinfoArr = $.parseJSON(KMLinfoArr);
let state;
for (let i = 0; i < keys.length; i++) {
state = keys[i];
for (let j = 0; j < KMLinfoArr.length; j++) {
if (KMLinfoArr[j].name === `${state}_Cities.kml`) {
//check the size in db against server - if different, update db
let stateObj = await idbKeyval.get(`${countryAbbr}_states_cities`, state);
if (stateObj.kmlsize !== KMLinfoArr[j].size) {
let kml = await fetch(`https://raw.githubusercontent.com/${repoOwner}/WME-Cities-Overlay/master/KMLs/${countryAbbr}/${state}_Cities.kml`);
if (state === countryAbbrObj.getAbbreviation(currState)) _kml = kml;
await idbKeyval.set(`${countryAbbr}_states_cities`, {
kml: kml,
state: state,
kmlsize: KMLinfoArr[j].size,
});
if (kmlCache[state] != null) kmlCache[state] = _kml;
if (updatedStates != '') updatedStates += `, ${state}`;
else updatedStates += state;
updatedCount += 1;
}
break;
}
}
}
if (updatedCount > 0) $('#WMECOupdateStatus').text(`${updatedCount} state file${updatedCount > 1 ? 's' : ''} updated - ${updatedStates}`);
else $('#WMECOupdateStatus').text('No updates available');
updateCitiesLayer();
}
/**
* Main initialisation routine. Registers the sidebar tab, creates the polygon and
* label map layers with their style rules, wires up event handlers, adds the layer
* switcher checkbox, and triggers the initial city polygon load if the layer is visible.
*/
async function init() {
initTab();
//I18n.translations[I18n.locale].layers.name[layerid] = "Cities Overlay";
const layerConfig = {
styleRules: [
{
// City polygons — stroke/fill only, no label text
predicate: (properties) => properties.type === 'city',
style: {
strokeDashstyle: 'solid',
strokeColor: '${dynamicStrokeColor}',
strokeOpacity: '${dynamicStrokeOpacity}',
strokeWidth: '${dynamicStrokeWidth}',
fillOpacity: '${dynamicFillOpacity}',
fillColor: '${dynamicFillColor}',
label: '',
},
},
],
styleContext: {
dynamicStrokeColor: (context) => {
if (_settings.HighlightFocusedCity && context.feature.id === currCity.featureId) {
return _settings.highlightColor;
}
return _settings.strokeColor;
},
dynamicFillColor: (context) => {
if (_settings.HighlightFocusedCity && context.feature.id === currCity.featureId) {
return _settings.highlightColor;
}
return _settings.fillColor;
},
dynamicStrokeWidth: (context) => {
if (_settings.HighlightFocusedCity && context.feature.id === currCity.featureId) {
return 6; // Highlight stroke width
}
return 2;
},
dynamicStrokeOpacity: () => _settings.strokeOpacity,
dynamicFillOpacity: () => (_settings.FillPolygons ? _settings.fillOpacity : 0),
},
};
wmeSDK.Map.addLayer({
layerName: layerid,
styleRules: layerConfig.styleRules,
styleContext: layerConfig.styleContext,
zIndexing: true,
});
// Labels layer — registered after polygon layer so it always renders on top
wmeSDK.Map.addLayer({
layerName: labelsLayerId,
styleRules: [
{
predicate: (properties) => properties.type === 'label',
style: {
pointRadius: 0,
label: '${getLabel}',
fontSize: '${getFontSize}',
fontFamily: 'Arial',
fontWeight: 'bold',
fontColor: '${getFontColor}',
labelOutlineColor: '${getLabelOutlineColor}',
labelOutlineWidth: '${getLabelOutlineWidth}',
labelYOffset: '${getLabelYOffset}',
labelAlign: 'cm',
},
},
],
styleContext: {
getLabel: ({ feature, zoomLevel }) => {
if (zoomLevel < 12) return '';
return feature?.properties?.labelText?.trim() ?? '';
},
getFontSize: ({ zoomLevel }) => {
if (_settings.labelFontSizeRelative) return `${Math.round(20 + (zoomLevel - 12) * 2)}px`;
return `${_settings.labelFontSize}px`;
},
getFontColor: () => (_settings.labelColorMatchStroke ? _settings.strokeColor : _settings.labelColor),
getLabelOutlineColor: () => (_settings.labelOutlineColorMatchStroke ? _settings.strokeColor : _settings.labelOutlineColor),
getLabelOutlineWidth: ({ zoomLevel }) => {
if (_settings.labelOutlineWidthRelative) return Math.max(1, Math.round((zoomLevel + 2) / 8));
return _settings.labelOutlineWidth;
},
getLabelYOffset: ({ zoomLevel }) => {
if (zoomLevel < 15) return 0;
if (zoomLevel < 18) return 5;
return 10;
},
},
zIndexing: true,
});
// Set visibility to true for the layer
wmeSDK.Map.setLayerVisibility({ layerName: layerid, visibility: _settings.layerVisible });
wmeSDK.Map.setLayerVisibility({ layerName: labelsLayerId, visibility: _settings.layerVisible });
wmeSDK.LayerSwitcher.addLayerCheckbox({ name: 'Cities Overlay' });
wmeSDK.LayerSwitcher.setLayerCheckboxChecked({ name: 'Cities Overlay', isChecked: _settings.layerVisible });
wmeSDK.Events.on({ eventName: 'wme-layer-checkbox-toggled', eventHandler: layerToggled });
wmeSDK.Events.on({ eventName: 'wme-map-move-end', eventHandler: onMapMove });
if (_settings.layerVisible) {
await updateCityPolygons();
currCity = findCurrCity();
if (_settings.AutoUpdateKMLs) {
updateAllMaps();