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