WME Mapraid Overlays

Mapraid overlays

当前为 2019-05-15 提交的版本,查看 最新版本

  1. // ==UserScript==
  2. // @name WME Mapraid Overlays
  3. // @namespace https://greasyfork.org/en/users/166843-wazedev
  4. // @version 2019.05.15.01
  5. // @description Mapraid overlays
  6. // @author JustinS83
  7. // @include https://www.waze.com/editor*
  8. // @include https://www.waze.com/*/editor*
  9. // @include https://beta.waze.com/editor*
  10. // @include https://beta.waze.com/*/editor*
  11. // @exclude https://www.waze.com/*user/editor*
  12. // @grant none
  13. // @require https://greasyfork.org/scripts/24851-wazewrap/code/WazeWrap.js
  14. // @contributionURL https://github.com/WazeDev/Thank-The-Authors
  15. // ==/UserScript==
  16.  
  17. /* global W */
  18. /* global OL */
  19. /* ecmaVersion 2017 */
  20. /* global $ */
  21. /* global I18n */
  22. /* global _ */
  23. /* global WazeWrap */
  24. /* global require */
  25. /* eslint curly: ["warn", "multi-or-nest"] */
  26.  
  27. (function() {
  28. 'use strict';
  29.  
  30. var _settings;
  31. var _settingsStoreName = '_wme_mapraid_overlays';
  32. var _kml;
  33. var _layerName = 'Cities Overlay';
  34. var _layer = null;
  35. var countryAbbr;
  36. var _origOpacity;
  37. var _mapraidNameMap = {};
  38.  
  39. function bootstrap(tries = 1) {
  40. if (W &&
  41. W.map &&
  42. W.model &&
  43. W.loginManager.user &&
  44. W.model.countries.top &&
  45. $ && WazeWrap.Ready)
  46. init();
  47. else if (tries < 1000)
  48. setTimeout(function () {bootstrap(tries++);}, 200);
  49. }
  50.  
  51. bootstrap();
  52.  
  53. function isChecked(checkboxId) {
  54. return $('#' + checkboxId).is(':checked');
  55. }
  56.  
  57. function setChecked(checkboxId, checked) {
  58. $('#' + checkboxId).prop('checked', checked);
  59. }
  60.  
  61. function loadSettings() {
  62. _settings = $.parseJSON(localStorage.getItem(_settingsStoreName));
  63. let _defaultsettings = {
  64. layerVisible: true,
  65. EnabledOverlays: {},
  66. HideCurrentArea: false
  67. };
  68. _settings = $.extend({}, _defaultsettings, _settings);
  69. }
  70.  
  71. function saveSettings() {
  72. if (localStorage) {
  73. var settings = {
  74. layerVisible: _layer.visibility,
  75. EnabledOverlays: _settings.EnabledOverlays,
  76. HideCurrentArea: _settings.HideCurrentArea
  77. };
  78. localStorage.setItem(_settingsStoreName, JSON.stringify(settings));
  79. }
  80. }
  81.  
  82. async function getKML(url){
  83. return await $.get(url);
  84. }
  85.  
  86. function GetFeaturesFromKMLString(strKML) {
  87. var format = new OL.Format.KML({
  88. 'internalProjection': W.map.baseLayer.projection,
  89. 'externalProjection': new OL.Projection("EPSG:4326"),
  90. 'extractStyles': true
  91. });
  92. return format.read(strKML);
  93. }
  94.  
  95. async function init(){
  96. loadSettings();
  97.  
  98. var layerid = 'wme_mapraid_overlays';
  99.  
  100. _layer = new OL.Layer.Vector("Mapraid Overlays", {
  101. rendererOptions: { zIndexing: true },
  102. uniqueName: layerid,
  103. layerGroup: 'mapraid_overlays',
  104. zIndex: -9999,
  105. visibility: _settings.layerVisible
  106. });
  107. I18n.translations[I18n.locale].layers.name[layerid] = "Mapraid Overlays";
  108. W.map.addLayer(_layer);
  109.  
  110. var $section = $("<div>", {style:"padding:8px 16px", id:"WMEMapraidOverlays"});
  111. $section.html([
  112. `<h4 style="margin-bottom:0px;"><b>WME Mapraid Overlays</b></h4>`,
  113. `<h6 style="margin-top:0px;">${GM_info.script.version}</h6>`,
  114. `<div><input type="checkbox" id="_cbMROHideCurrentArea" class="wmemroSettingsCheckbox" /><label for="_cbMROHideCurrentArea">Hide fill for current area</label></div>`,
  115. `<div id="divWMEMROAvailableOverlays"><label>Available overlays</label> <select id="mroOverlaySelect" style="min-width:125px;"></select><i class="fa fa-plus fa-lg" id="mroAddOverlay" aria-hidden="true" style="color:green; cursor:pointer;"></i></div>`,
  116. '<div id="currOverlays"></div>',
  117. '<div style="position:absolute; bottom:0;">Generate new mapraid overlays at <a href="http://wazedev.com/mapraidgenerator.html" target="_blank">http://wazedev.com/mapraidgenerator.html</a></div>',
  118. '</div>'
  119. ].join(' '));
  120.  
  121. new WazeWrap.Interface.Tab('MRO', $section.html(), init2);
  122. }
  123.  
  124. async function getAvailableOverlays(){
  125. $('#mroOverlaySelect').innerHTML = "";
  126. countryAbbr = W.model.countries.top.abbr;
  127. let KMLinfoArr = await $.get(`https://api.github.com/repos/WazeDev/WME-Mapraid-Overlays/contents/KMLs/${countryAbbr}`);
  128. let overlaysSelect = $('<div>');
  129. overlaysSelect.html([
  130. '<option selected disabled hidden style="display: none" value=""></option>',
  131. `${KMLinfoArr.map(function(obj){
  132. let fileName = obj.name.replace(".kml", "");
  133. if(!_settings.EnabledOverlays[fileName])
  134. return `<option value="${fileName}">${fileName}</option>`;
  135. })}`,
  136. '</select>'
  137. ].join(''));
  138. $('#mroOverlaySelect')[0].innerHTML = overlaysSelect.html();
  139. }
  140.  
  141. function updatePolygons(newKML, mapraidName){
  142. var _features = GetFeaturesFromKMLString(newKML);
  143.  
  144. for(let i=0; i< _features.length; i++){
  145. _features[i].attributes.name = _features[i].attributes.name.replace('<at><openparen>', '').replace('<closeparen>','');
  146. _features[i].style.label = _features[i].attributes.name;
  147. _features[i].style.labelOutlineColor= '#000000';
  148. _features[i].style.labelOutlineWidth= 4;
  149. _features[i].style.labelAlign= 'cm';
  150. _features[i].style.fontSize= "16px";
  151. _features[i].style.fontColor= _features[i].style.fillColor;//"#ffffff";
  152. _features[i].attributes.mapraidName = mapraidName;
  153.  
  154. if(!_settings.EnabledOverlays[mapraidName].fillAreas){
  155. if(!_origOpacity)
  156. _origOpacity = _features[i].style.fillOpacity;
  157. _features[i].style.fillOpacity = 0;
  158. }
  159. }
  160.  
  161. _layer.addFeatures(_features);
  162. }
  163.  
  164. function hex_is_light(color) {
  165. const hex = color.replace('#', '');
  166. const c_r = parseInt(hex.substr(0, 2), 16);
  167. const c_g = parseInt(hex.substr(2, 2), 16);
  168. const c_b = parseInt(hex.substr(4, 2), 16);
  169. debugger;
  170. const brightness = ((c_r * 299) + (c_g * 587) + (c_b * 114)) / 1000;
  171. return brightness > 70;
  172. }
  173.  
  174. async function BuildEnabledOverlays(mapraidName){
  175. let kml;
  176. try{
  177. kml = await getKML(encodeURI(`https://raw.githubusercontent.com/WazeDev/WME-Mapraid-Overlays/master/KMLs/${countryAbbr}/${mapraidName}.kml`));
  178. }
  179. catch(err){
  180. return;
  181. console.error(err);
  182. }
  183. let kmlObj = $($.parseXML(kml));
  184. let RaidAreas = $(kmlObj).find('Placemark');
  185.  
  186. let $newRaidSection = $('<div>');
  187. $newRaidSection.html([
  188. `<fieldset style="border:1px solid silver; padding:8px; border-radius:4px; position:relative;"><legend style="margin-bottom:0px; borer-bottom-style:none; width:auto;"><h4>${mapraidName}</h4></legend>`,
  189. `<i class="fa fa-minus fa-lg" id="mroRemoveOverlay${mapraidName.replace(/\s/g, "_")}" aria-hidden="true" style="color:red; position:absolute; cursor:pointer; top:10px; right:5px;"></i>`,
  190. `<div><input type="checkbox" id="_cbMROFillRaidArea${mapraidName.replace(/\s/g, "_")}" ${_settings.EnabledOverlays[mapraidName].fillAreas ? 'checked' : ''} /><label for="_cbMROFillRaidArea${mapraidName.replace(/\s/g, "_")}">Fill raid area</label></div>`,
  191. `Jump to <select id="${mapraidName.replace(/\s/g, "_")}_Areas">${
  192. function(){
  193. let names = $(RaidAreas).find('name');
  194. let options = "";
  195. for(let i=0; i<names.length; i++)
  196. options += `<option>${$(names[i]).text()}</option>`;
  197. return options;
  198. }()
  199. }</select>`,
  200. `<i class="fa fa-share" aria-hidden="true" style="color:green; cursor:pointer;" id="JumpTo${mapraidName.replace(/\s/g, "_")}"></i>`,
  201. '</fieldset>'
  202. ].join(''));
  203.  
  204. $(`#mroOverlaySelect option[value="${mapraidName}"]`).remove(); //remove this option from the list
  205. $('#currOverlays').append($newRaidSection.html()); //add the mapraid section
  206.  
  207. $('[id^="_cbMROFillRaidArea"]').change(function(){
  208. let mapraid = this.id.replace("_cbMROFillRaidArea", "");
  209. _settings.EnabledOverlays[_mapraidNameMap[mapraid]].fillAreas = isChecked(this.id);
  210. saveSettings();
  211. });
  212.  
  213. $('[id^="mroRemoveOverlay"]').click(function(){
  214. let mapraid = this.id.replace("mroRemoveOverlay", "");
  215. $(this).parent().remove();
  216.  
  217. delete _settings.EnabledOverlays[_mapraidNameMap[mapraid]];
  218. saveSettings();
  219.  
  220. let deleteFeatures = [];
  221. for(let i=0; i < _layer.features.length; i++){ //delete the features from the layer
  222. if(_layer.features[i].attributes.mapraidName === _mapraidNameMap[mapraid])
  223. deleteFeatures.push(_layer.features[i]);
  224. }
  225. _layer.removeFeatures(deleteFeatures);
  226. getAvailableOverlays();
  227. });
  228.  
  229. $('[id^=_cbMROFillRaidArea]').change(function(){
  230. let mapraid = this.id.replace("_cbMROFillRaidArea", "");
  231. for(let i=0; i<_layer.features.length; i++){
  232. if(_layer.features[i].attributes.mapraidName.replace(/\s/g, "_") === mapraid){
  233. if(!_origOpacity)
  234. _origOpacity = _layer.features[i].style.fillOpacity;
  235. _layer.features[i].style.fillOpacity = isChecked(this.id) ? _origOpacity : 0;
  236. _layer.redraw();
  237. }
  238. }
  239. });
  240.  
  241. $('[id^="JumpTo"]').click(function(){
  242. //jump to the appropriate area - look up the area in the layer features and jump to the centroid.
  243. let raidArea = this.id.replace("JumpTo", "");
  244. for(let i=0; i<_layer.features.length; i++){
  245. if(_layer.features[i].attributes.mapraidName.replace(/\s/g, "_") === raidArea){
  246. let selectedArea = $(`#${raidArea.replace(/\s/g, "_")}_Areas`).val();
  247. if(_layer.features[i].attributes.name === selectedArea){
  248. let centroid = _layer.features[i].geometry.getCentroid();
  249. W.map.setCenter([centroid.x, centroid.y], W.map.zoom)
  250. break;
  251. }
  252. }
  253. }
  254.  
  255. });
  256.  
  257. updatePolygons(kml, mapraidName);
  258. }
  259.  
  260. function HandleMoveZoom(){
  261. //display the current MR area in the title bar
  262. //hide the current MR area fill (if setting is enabled)
  263.  
  264. if($('#mrodivCurrMapraidArea').length === 0){
  265. var $section = $("<div>");
  266. $section.html([
  267. '<div id="mrodivCurrMapraidArea" style="font-size: 16px; font-weight:bold; display:inline-block; margin-left:10px;">',
  268. '<span id="mroCurrAreaTopbar"></span>',
  269. '</div>'
  270. ].join(' '));
  271.  
  272. $('.topbar').append($section.html());
  273. }
  274.  
  275. let center = new OL.Geometry.Point(W.map.center.lon,W.map.center.lat);
  276.  
  277. for (var i=0;i<_layer.features.length;i++){
  278. var feature = _layer.features[i];
  279. if(_origOpacity && _settings.EnabledOverlays[feature.attributes.mapraidName].fillAreas)
  280. feature.style.fillOpacity = _origOpacity;
  281. if(feature.geometry.intersects(center)){
  282. $('#mroCurrAreaTopbar').text(feature.attributes.name);
  283. $('#mroCurrAreaTopbar').css('color', feature.style.fillColor);
  284.  
  285. if(!hex_is_light(feature.style.fillColor))
  286. $('#mroCurrAreaTopbar').css('text-shadow', '-1px 0 #efefef, 0 1px #efefef, 1px 0 #efefef, 0 -1px #efefef');
  287. else
  288. $('#mroCurrAreaTopbar').css('text-shadow', '-1px 0 black, 0 1px black, 1px 0 black, 0 -1px black');
  289.  
  290.  
  291. if(_settings.HideCurrentArea){
  292. if(!_origOpacity)
  293. _origOpacity = feature.style.fillOpacity;
  294. if(feature.style.fillOpacity > 0)
  295. feature.style.fillOpacity = 0;
  296. }
  297. }
  298. }
  299. _layer.redraw();
  300. }
  301.  
  302. function init2(){
  303. getAvailableOverlays();
  304.  
  305. $.each(_settings.EnabledOverlays, function(k, v){
  306. if(!_mapraidNameMap[k.replace(/\s/g, "_")])
  307. _mapraidNameMap[k.replace(/\s/g, "_")] = k;
  308. BuildEnabledOverlays(k);
  309.  
  310. });
  311.  
  312. $('#mroAddOverlay').click(async function(){
  313. if($('#mroOverlaySelect').val() !== null){
  314. let raid = $('#mroOverlaySelect').val();
  315. _settings.EnabledOverlays[raid] = {fillAreas: true};
  316.  
  317. BuildEnabledOverlays(raid);
  318. if(!_mapraidNameMap[raid.replace(/\s/g, "_")])
  319. _mapraidNameMap[raid.replace(/\s/g, "_")] = raid;
  320.  
  321. saveSettings();
  322. }
  323. });
  324.  
  325. $('.wmemroSettingsCheckbox').change(function(){
  326. var settingName = $(this)[0].id.substr(6);
  327. _settings[settingName] = this.checked;
  328. saveSettings();
  329. });
  330.  
  331. $('#_cbMROHideCurrentArea').change(function(){
  332. HandleMoveZoom();
  333. });
  334.  
  335. WazeWrap.Events.register("zoomend", null, HandleMoveZoom);
  336. WazeWrap.Events.register("moveend", null, HandleMoveZoom);
  337.  
  338. setChecked('_cbMROHideCurrentArea', _settings.HideCurrentArea);
  339. HandleMoveZoom();
  340. }
  341.  
  342. })();