WME Mapraid Overlays

Mapraid overlays

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

  1. // ==UserScript==
  2. // @name WME Mapraid Overlays
  3. // @namespace https://greasyfork.org/en/users/166843-wazedev
  4. // @version 2019.05.10.03
  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.  
  155. _layer.addFeatures(_features);
  156. }
  157.  
  158. async function BuildEnabledOverlays(mapraidName){
  159. let kml;
  160. try{
  161. kml = await getKML(encodeURI(`https://raw.githubusercontent.com/WazeDev/WME-Mapraid-Overlays/master/KMLs/${countryAbbr}/${mapraidName}.kml`));
  162. }
  163. catch(err){
  164. return;
  165. console.error(err);
  166. }
  167. let kmlObj = $($.parseXML(kml));
  168. let RaidAreas = $(kmlObj).find('Placemark');
  169.  
  170. let $newRaidSection = $('<div>');
  171. $newRaidSection.html([
  172. `<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>`,
  173. `<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>`,
  174. `<div><input type="checkbox" id="_cbMROFillRaidArea${mapraidName.replace(/\s/g, "_")}" checked /><label for="_cbMROFillRaidArea${mapraidName.replace(/\s/g, "_")}">Fill raid area</label></div>`,
  175. `Jump to <select id="${mapraidName.replace(/\s/g, "_")}_Areas">${
  176. function(){
  177. let names = $(RaidAreas).find('name');
  178. let options = "";
  179. for(let i=0; i<names.length; i++)
  180. options += `<option>${$(names[i]).text()}</option>`;
  181. return options;
  182. }()
  183. }</select>`,
  184. `<i class="fa fa-share" aria-hidden="true" style="color:green; cursor:pointer;" id="JumpTo${mapraidName.replace(/\s/g, "_")}"></i>`,
  185. '</fieldset>'
  186. ].join(''));
  187.  
  188. $(`#mroOverlaySelect option[value="${mapraidName}"]`).remove(); //remove this option from the list
  189. $('#currOverlays').append($newRaidSection.html()); //add the mapraid section
  190.  
  191. $('[id^="mroRemoveOverlay"]').click(function(){
  192. let mapraid = this.id.replace("mroRemoveOverlay", "");
  193. $(this).parent().remove();
  194.  
  195. delete _settings.EnabledOverlays[_mapraidNameMap[mapraid]];
  196. saveSettings();
  197.  
  198. let deleteFeatures = [];
  199. for(let i=0; i < _layer.features.length; i++){ //delete the features from the layer
  200. if(_layer.features[i].attributes.mapraidName === _mapraidNameMap[mapraid])
  201. deleteFeatures.push(_layer.features[i]);
  202. }
  203. _layer.removeFeatures(deleteFeatures);
  204. getAvailableOverlays();
  205. });
  206.  
  207. $('[id^=_cbMROFillRaidArea]').change(function(){
  208. let mapraid = this.id.replace("_cbMROFillRaidArea", "");
  209. for(let i=0; i<_layer.features.length; i++){
  210. if(_layer.features[i].attributes.mapraidName.replace(/\s/g, "_") === mapraid){
  211. if(!_origOpacity)
  212. _origOpacity = _layer.features[i].style.fillOpacity;
  213. _layer.features[i].style.fillOpacity = isChecked(this.id) ? _origOpacity : 0;
  214. _layer.redraw();
  215. }
  216. }
  217. });
  218.  
  219. $('[id^="JumpTo"]').click(function(){
  220. //jump to the appropriate area - look up the area in the layer features and jump to the centroid.
  221. let raidArea = this.id.replace("JumpTo", "");
  222. for(let i=0; i<_layer.features.length; i++){
  223. if(_layer.features[i].attributes.mapraidName.replace(/\s/g, "_") === raidArea){
  224. let selectedArea = $(`#${raidArea.replace(/\s/g, "_")}_Areas`).val();
  225. if(_layer.features[i].attributes.name === selectedArea){
  226. let centroid = _layer.features[i].geometry.getCentroid();
  227. W.map.setCenter([centroid.x, centroid.y], W.map.zoom)
  228. break;
  229. }
  230. }
  231. }
  232.  
  233. });
  234.  
  235. updatePolygons(kml, mapraidName);
  236. }
  237.  
  238. function HandleMoveZoom(){
  239. //display the current MR area in the title bar
  240. //hide the current MR area fill (if setting is enabled)
  241.  
  242. if($('#mrodivCurrMapraidArea').length === 0){
  243. var $section = $("<div>");
  244. $section.html([
  245. '<div id="mrodivCurrMapraidArea" style="font-size: 14px; font-weight:bold; display:inline-block; margin-left:10px;">',
  246. '<span id="mroCurrAreaTopbar"></span>',
  247. '</div>'
  248. ].join(' '));
  249.  
  250. $('.topbar').append($section.html());
  251. }
  252.  
  253. let center = new OL.Geometry.Point(W.map.center.lon,W.map.center.lat);
  254.  
  255. for (var i=0;i<_layer.features.length;i++){
  256. var feature = _layer.features[i];
  257. if(_origOpacity)
  258. feature.style.fillOpacity = _origOpacity;
  259. if(feature.geometry.intersects(center)){
  260. $('#mroCurrAreaTopbar').text(feature.attributes.name);
  261. $('#mroCurrAreaTopbar').css('color', feature.style.fillColor);
  262.  
  263. if(_settings.HideCurrentArea){
  264. if(!_origOpacity)
  265. _origOpacity = feature.style.fillOpacity;
  266. if(feature.style.fillOpacity > 0)
  267. feature.style.fillOpacity = 0;
  268. }
  269. }
  270. }
  271. _layer.redraw();
  272. }
  273.  
  274. function init2(){
  275. getAvailableOverlays();
  276.  
  277. $.each(_settings.EnabledOverlays, function(k, v){
  278. BuildEnabledOverlays(k);
  279. if(!_mapraidNameMap[k.replace(/\s/g, "_")])
  280. _mapraidNameMap[k.replace(/\s/g, "_")] = k;
  281.  
  282. });
  283.  
  284. $('#mroAddOverlay').click(async function(){
  285. if($('#mroOverlaySelect').val() !== null){
  286. let raid = $('#mroOverlaySelect').val();
  287.  
  288. BuildEnabledOverlays(raid);
  289. if(!_mapraidNameMap[raid.replace(/\s/g, "_")])
  290. _mapraidNameMap[raid.replace(/\s/g, "_")] = raid;
  291.  
  292. _settings.EnabledOverlays[raid] = {fillAreas: true};
  293. saveSettings();
  294. }
  295. });
  296.  
  297. $('.wmemroSettingsCheckbox').change(function(){
  298. var settingName = $(this)[0].id.substr(6);
  299. _settings[settingName] = this.checked;
  300. saveSettings();
  301. });
  302.  
  303. $('#_cbMROHideCurrentArea').change(function(){
  304. HandleMoveZoom();
  305. });
  306.  
  307. WazeWrap.Events.register("zoomend", null, HandleMoveZoom);
  308. WazeWrap.Events.register("moveend", null, HandleMoveZoom);
  309.  
  310. setChecked('_cbMROHideCurrentArea', _settings.HideCurrentArea);
  311. HandleMoveZoom();
  312. }
  313.  
  314. })();