Geoguessr Map-Making Auto-Tag

Tag your street views by date, exactTime, address, generation, elevation

当前为 2024-06-13 提交的版本,查看 最新版本

  1. // ==UserScript==
  2. // @name Geoguessr Map-Making Auto-Tag
  3. // @namespace https://www.geoguessr.com/user/6494f9bbab07ca3ea843220f
  4. // @version 3.83.2
  5. // @description Tag your street views by date, exactTime, address, generation, elevation
  6. // @author KaKa
  7. // @match https://map-making.app/maps/*
  8. // @grant GM_setClipboard
  9. // @grant GM_xmlhttpRequest
  10. // @require https://cdn.jsdelivr.net/npm/sweetalert2@11
  11. // @license MIT
  12. // @icon https://www.svgrepo.com/show/423677/tag-price-label.svg
  13. // ==/UserScript==
  14.  
  15. (function() {
  16. 'use strict';
  17. let accuracy=60 /* You could modifiy accuracy here, default setting is 1 minutes */
  18. let tagBox = ['Year', 'Month','Day', 'Time','Country', 'Subdivision', 'Locality', 'Generation', 'Elevation','Type']
  19. let mapData
  20.  
  21. function getMap() {
  22. return new Promise(function(resolve, reject) {
  23. var requestURL = window.location.origin + "/api" + window.location.pathname + "/locations";
  24.  
  25. GM_xmlhttpRequest({
  26. method: "GET",
  27. url: requestURL,
  28. onload: function(response) {
  29.  
  30. if (response.status === 200) {
  31.  
  32. try {
  33. var jsonData = JSON.parse(response.responseText);
  34. resolve(jsonData);
  35. } catch (error) {
  36. console.error("Error parsing JSON:", error);
  37.  
  38. reject("Error parsing JSON data!");
  39. }
  40. } else {
  41.  
  42. console.error("HTTP Error:", response.status);
  43. reject("HTTP Error!");
  44. }
  45. },
  46. onerror: function(error) {
  47.  
  48. console.error("Request Error:", error);
  49. reject("Error fetching meta data of the map!");
  50. }
  51. });
  52. });
  53. }
  54.  
  55. async function getSelection() {
  56. return new Promise((resolve, reject) => {
  57. var exportButtonText = 'Export';
  58. var buttons = document.querySelectorAll('button.button');
  59.  
  60. for (var i = 0; i < buttons.length; i++) {
  61. if (buttons[i].textContent.trim() === exportButtonText) {
  62. buttons[i].click();
  63. var modalDialog = document.querySelector('.modal__dialog.export-modal');
  64. }
  65. }
  66.  
  67. setTimeout(() => {
  68. const radioButton = document.querySelector('input[type="radio"][name="selection"][value="1"]');
  69. const spanText = radioButton.nextElementSibling.textContent.trim();
  70. if (spanText==="Export selection (0 locations)") {
  71. swal.fire('Selection not found!', 'Please select at least one location as selection!','warning')
  72. reject(new Error('Export selection is empty!'));
  73. }
  74. if (radioButton) radioButton.click()
  75. else{
  76. reject(new Error('Radio button not found'));}
  77. }, 100);
  78.  
  79.  
  80. setTimeout(() => {
  81. const copyButton = document.querySelector('.export-modal__export-buttons button:first-of-type');
  82. if (!copyButton) {
  83. reject(new Error('Copy button not found'));
  84. }
  85. copyButton.click();
  86.  
  87. }, 300);
  88. setTimeout(() => {
  89. const closeButton = document.querySelector('.modal__close');
  90. if (closeButton) closeButton.click();
  91. else reject(new Error('Close button not found'));
  92. }, 600);
  93.  
  94. setTimeout(async () => {
  95. try {
  96. const data = await navigator.clipboard.readText()
  97. const selection = JSON.parse(data);
  98. resolve(selection);
  99. } catch (error) {
  100. console.error("Error getting selection:", error);
  101. reject(error);
  102. }
  103. }, 1000);
  104. });
  105. }
  106.  
  107. function matchSelection(selection, locations) {
  108. const matchingLocations = [];
  109. const customCoordinates = selection.customCoordinates;
  110. for (const coord of customCoordinates) {
  111. const lat = coord.lat;
  112. const lng = coord.lng;
  113. for (const loc of locations) {
  114. const location = loc.location;
  115. if (location.lat === lat && location.lng === lng) {
  116. matchingLocations.push(loc);
  117. }
  118. }
  119. }
  120. return matchingLocations;
  121. }
  122.  
  123. function findRange(elevation, ranges) {
  124. for (let i = 0; i < ranges.length; i++) {
  125. const range = ranges[i];
  126. if (elevation >= range.min && elevation <= range.max) {
  127. return `${range.min}-${range.max}m`;
  128. }
  129. }
  130. if (!elevation) {
  131. return 'noElevation';
  132. }
  133. return `${JSON.stringify(elevation)}m`;
  134. }
  135.  
  136. function updateSelection(entries) {
  137. var requestURL = window.location.origin + "/api" + window.location.pathname + "/locations";
  138. var payload = {
  139. edits: []
  140. };
  141.  
  142. entries.forEach(function(entry) {
  143. var createEntry = {
  144. id: -1,
  145. author: entry.author,
  146. mapId: entry.mapId,
  147. location: entry.location,
  148. panoId: entry.panoId,
  149. panoDate: entry.panoDate,
  150. heading: entry.heading,
  151. pitch: entry.pitch,
  152. zoom: entry.zoom,
  153. tags: entry.tags,
  154. flags: entry.flags,
  155. createdAt: entry.createdAt,
  156.  
  157. };
  158. payload.edits.push({
  159. action: {
  160. type: 3
  161. },
  162. create: [createEntry],
  163. remove: [entry.id]
  164. });
  165. });
  166.  
  167. var xhr = new XMLHttpRequest();
  168. xhr.open("POST", requestURL);
  169. xhr.setRequestHeader("Content-Type", "application/json");
  170.  
  171. xhr.onload = function() {
  172. if (xhr.status >= 200 && xhr.status < 300) {
  173. console.log("Request succeeded");
  174. } else {
  175. console.error("Request failed with status", xhr.status);
  176. }
  177. };
  178.  
  179. xhr.onerror = function() {
  180. console.error("Request failed");
  181. swal.fire({
  182. icon: 'error',
  183. title: 'Oops...',
  184. text: 'Failed to update the map! Please get JSON data from your clipboard.'
  185. });
  186. };
  187.  
  188. xhr.send(JSON.stringify(payload));
  189. }
  190.  
  191. async function runScript(tags,sR) {
  192. let taggedLocs=[];
  193. let exportMode,selections
  194. const { value: option,dismiss: inputDismiss } = await Swal.fire({
  195. title: 'Export',
  196. text: 'Do you want to update and save your map? If you click "Cancel", the script will just paste JSON data to the clipboard after finish tagging.',
  197. icon: 'question',
  198. showCancelButton: true,
  199. showCloseButton:true,
  200. allowOutsideClick: false,
  201. confirmButtonColor: '#3085d6',
  202. cancelButtonColor: '#d33',
  203. confirmButtonText: 'Yes',
  204. cancelButtonText: 'Cancel'
  205. });
  206. if (option) {
  207. exportMode='save'
  208. }
  209. if(!selections){
  210. const selectedLocs=await getSelection()
  211. mapData=await getMap()
  212. selections=await matchSelection(selectedLocs,mapData)
  213. }
  214.  
  215. async function UE(t, e, s, d) {
  216. try {
  217. const r = `https://maps.googleapis.com/$rpc/google.internal.maps.mapsjs.v1.MapsJsInternalService/${t}`;
  218. let payload = createPayload(t, e,s,d);
  219.  
  220. const response = await fetch(r, {
  221. method: "POST",
  222. headers: {
  223. "content-type": "application/json+protobuf",
  224. "x-user-agent": "grpc-web-javascript/0.1"
  225. },
  226. body: payload,
  227. mode: "cors",
  228. credentials: "omit"
  229. });
  230.  
  231. if (!response.ok) {
  232. throw new Error(`HTTP error! status: ${response.status}`);
  233. } else {
  234. return await response.json();
  235. }
  236. } catch (error) {
  237. console.error(`There was a problem with the UE function: ${error.message}`);
  238. }
  239. }
  240.  
  241. function createPayload(mode,coorData,s,d) {
  242. let payload;
  243.  
  244. if (mode === 'GetMetadata') {
  245. payload = [["apiv3",null,null,null,"US",null,null,null,null,null,[[0]]],["en","US"],[[[2,coorData]]],[[1,2,3,4,8,6]]];
  246. } else if (mode === 'SingleImageSearch') {
  247. var lat = coorData.location.lat;
  248. var lng = coorData.location.lng;
  249. lat = lat % 1 !== 0 && lat.toString().split('.')[1].length >6 ? parseFloat(lat.toFixed(6)) : lat;
  250. lng = lng % 1 !== 0 && lng.toString().split('.')[1].length > 6 ? parseFloat(lng.toFixed(6)) : lng;
  251. if(s&&d){
  252. payload=[["apiv3"],[[null,null,lat,lng],10],[[null,null,null,null,null,null,null,null,null,null,[s,d]],null,null,null,null,null,null,null,[2],null,[[[2,true,2]]]],[[2,6]]]
  253. }else{
  254. payload =[["apiv3",null,null,null,"US",null,null,null,null,null, [[0]]],
  255. [[null,null,lat,lng],50],
  256. [null,["en","US"],null,null,null,null,null,null,[2],null,[[[2,1,2],[3,1,2],[10,1,2]]]], [[1,2,3,4,8,6]]];}
  257. } else {
  258. throw new Error("Invalid mode!");
  259. }
  260. return JSON.stringify(payload);
  261. }
  262.  
  263. function monthToTimestamp(m) {
  264.  
  265. const [year, month] = m.split('-');
  266.  
  267. const startDate =Math.round( new Date(year, month-1,1).getTime()/1000);
  268.  
  269. const endDate =Math.round( new Date(year, month, 1).getTime()/1000)-1;
  270.  
  271. return { startDate, endDate };
  272. }
  273.  
  274. async function binarySearch(c, start,end) {
  275. let capture
  276. let response
  277. while (end - start >= accuracy) {
  278. let mid= Math.round((start + end) / 2);
  279. response = await UE("SingleImageSearch", c, start,end);
  280. if (response&&response[0][2]== "Search returned no images." ){
  281. start=mid+start-end
  282. end=start-mid+end
  283. mid=Math.round((start+end)/2)
  284. } else {
  285. start=mid
  286. mid=Math.round((start+end)/2)
  287. }
  288. capture=mid
  289. }
  290.  
  291. return capture
  292. }
  293.  
  294. function getMetaData(svData) {
  295. if (svData) {
  296. let levelId=svData.dn
  297. let year = 'noyear',month = 'nomonth'
  298. let panoType='Unofficial'
  299. let subdivision='nosub',locality='nolocality'
  300. let coverageCount='0'
  301. if (svData.imageDate) {
  302. const matchYear = svData.imageDate.match(/\d{4}/);
  303. if (matchYear) {
  304. year = matchYear[0];
  305. }
  306.  
  307. const matchMonth = svData.imageDate.match(/-(\d{2})/);
  308. if (matchMonth) {
  309. month = matchMonth[1];
  310. }
  311. }
  312.  
  313. if (svData.copyright.includes('Google')) {
  314. panoType = 'Official';
  315. }
  316. if (svData.time){
  317. coverageCount = svData.time.length.toString();
  318. }
  319. if(svData.location.description){
  320. let parts = svData.location.description.split(',');
  321. if(parts.length > 1){
  322. subdivision = parts[parts.length-1].trim();
  323. locality = parts[parts.length-2].trim();
  324. } else {
  325. subdivision = svData.location.description;
  326.  
  327. }
  328. }
  329. return [year,month,panoType,subdivision,locality,levelId,coverageCount]
  330. }
  331.  
  332. else{
  333. return null}
  334. }
  335.  
  336. function getGeneration(svData,country) {
  337.  
  338. if (svData&&svData.tiles) {
  339. if (svData.tiles.worldSize.height === 1664) { // Gen 1
  340. return 'Gen1';
  341. } else if (svData.tiles.worldSize.height === 6656) { // Gen 2 or 3
  342.  
  343. let lat;
  344. for (let key in svData.Sv) {
  345. lat = svData.Sv[key].lat;
  346. break;
  347. }
  348.  
  349. let date;
  350. if (svData.imageDate) {
  351. date = new Date(svData.imageDate);
  352. } else {
  353. date = 'nodata';
  354. }
  355.  
  356. if (date!=='nodata'&&((country === 'BD' && (date >= new Date('2021-04'))) ||
  357. (country === 'EC' && (date >= new Date('2022-03'))) ||
  358. (country === 'FI' && (date >= new Date('2020-09'))) ||
  359. (country === 'IN' && (date >= new Date('2021-10'))) ||
  360. (country === 'LK' && (date >= new Date('2021-02'))) ||
  361. (country === 'KH' && (date >= new Date('2022-10'))) ||
  362. (country === 'LB' && (date >= new Date('2021-05'))) ||
  363. (country === 'NG' && (date >= new Date('2021-06'))) ||
  364. (country === 'ST') ||
  365. (country === 'US' && lat > 52 && (date >= new Date('2019-01'))))) {
  366. return 'Shitcam';
  367. }
  368.  
  369. let gen2Countries = ['AU', 'BR', 'CA', 'CL', 'JP', 'GB', 'IE', 'NZ', 'MX', 'RU', 'US', 'IT', 'DK', 'GR', 'RO',
  370. 'PL', 'CZ', 'CH', 'SE', 'FI', 'BE', 'LU', 'NL', 'ZA', 'SG', 'TW', 'HK', 'MO', 'MC', 'SM',
  371. 'AD', 'IM', 'JE', 'FR', 'DE', 'ES', 'PT'];
  372. if (gen2Countries.includes(country)) {
  373.  
  374. return 'Gen2or3';
  375. }
  376. else{
  377. return 'Gen3';}
  378. }
  379. else if(svData.tiles.worldSize.height === 8192){
  380. return 'Gen4';
  381. }
  382. }
  383. return 'Unknown';
  384. }
  385.  
  386. async function getLocal(coord, timestamp) {
  387. const apiUrl = "https://api.geotimezone.com/public/timezone?";
  388. const systemTimezoneOffset = -new Date().getTimezoneOffset() * 60;
  389.  
  390. try {
  391. const [lat, lng] = coord;
  392. const url = `${apiUrl}latitude=${lat}&longitude=${lng}`;
  393.  
  394. const responsePromise = new Promise((resolve, reject) => {
  395. GM_xmlhttpRequest({
  396. method: "GET",
  397. url: url,
  398. responseType: "json",
  399. onload: function(response) {
  400. if (response.status >= 200 && response.status < 300) {
  401. resolve(response.response);
  402. } else {
  403. Swal.fire('Error fecthing exact time!', "Request failed: " + response.statusText,'error')
  404. reject(new Error("Request failed: " + response.statusText));
  405. }
  406. },
  407. onerror: function(error) {
  408. reject(new Error("There was a network error: " + error));
  409. }
  410. });
  411. });
  412.  
  413. function extractOffset(text) {
  414. const regex = /UTC[+-]?\d+/;
  415. const match = text.match(regex);
  416. if (match) {
  417. return parseInt(match[0].substring(3));
  418. } else {
  419. return null;
  420. }
  421. }
  422. const data = await responsePromise;
  423. const offset = extractOffset(data.offset);
  424. const targetTimezoneOffset = offset * 3600;
  425. const offsetDiff = systemTimezoneOffset - targetTimezoneOffset;
  426. const convertedTimestamp = Math.round(timestamp - offsetDiff);
  427. return convertedTimestamp;
  428. } catch (error) {
  429. throw error;
  430. }
  431. }
  432.  
  433. var CHUNK_SIZE = 1200;
  434. if (tags.includes('time')){
  435. CHUNK_SIZE = 500
  436. }
  437. var promises = [];
  438.  
  439. async function processCoord(coord, tags, svData,ccData) {
  440. if (svData){
  441. let meta=getMetaData(svData)
  442. let yearTag=meta[0]
  443. let monthTag=meta[1]
  444. let typeTag=meta[2]
  445. let subdivisionTag=meta[3]
  446. let localityTag=meta[4]
  447. let countryTag,elevationTag
  448. let genTag
  449. let trekkerTag=meta[5]
  450. let coverageTag=meta[6]
  451. let dayTag,timeTag,exactTime,timeRange
  452. var date=monthToTimestamp(meta[0]+'-'+meta[1])
  453.  
  454. if(tags.includes('day')||tags.includes('time')){
  455. exactTime=await binarySearch(coord, date.startDate,date.endDate)
  456. if (exactTime<=date.startDate||exactTime>=date.endDate){
  457. exactTime=null
  458. }
  459. }
  460.  
  461. if(!exactTime){dayTag='noday'
  462. timeTag='notime'
  463. }
  464. else{
  465.  
  466. const currentDate = new Date();
  467. const currentOffset =-(currentDate.getTimezoneOffset())*60
  468. const dayOffset = currentOffset-Math.round((coord.location.lng / 15) * 3600);
  469. const LocalDay=new Date(Math.round(exactTime-dayOffset)*1000)
  470. dayTag = LocalDay.toISOString().split('T')[0];
  471.  
  472. if(tags.includes('time')) {
  473.  
  474. var localTime=await getLocal([coord.location.lat,coord.location.lng],exactTime)
  475. var timeObject=new Date(localTime*1000)
  476. timeTag =`${timeObject.getHours().toString().padStart(2, '0')}:${timeObject.getMinutes().toString().padStart(2, '0')}:${timeObject.getSeconds().toString().padStart(2, '0')}`;
  477. var hour = timeObject.getHours();
  478.  
  479. if (hour < 11) {
  480. timeRange = 'Morning';
  481. } else if (hour >= 11 && hour < 13) {
  482. timeRange = 'Noon';
  483. } else if (hour >= 13 && hour < 17) {
  484. timeRange = 'Afternoon';
  485. } else if(hour >= 17 && hour < 19) {
  486. timeRange = 'Evening';
  487. }
  488. else{
  489. timeRange = 'Night';
  490. }
  491. }
  492. }
  493. if (ccData){
  494. try {
  495. countryTag = ccData[1][0][5][0][1][4]
  496. elevationTag=ccData[1][0][5][0][1][1][0]
  497. }
  498. catch (error) {
  499. try {
  500. countryTag = ccData[1][5][0][1][4]
  501. elevationTag=ccData[1][5][0][1][1][0]
  502. } catch (error) {
  503. countryTag='nocountry'
  504. elevationTag='noelevation'
  505. }
  506. }
  507. if (!countryTag)countryTag='nocountry'
  508. if (!elevationTag)elevationTag='noelevation'
  509. else{
  510. elevationTag=Math.round(elevationTag*100)/100
  511. if(sR){
  512. elevationTag=findRange(elevationTag,sR)
  513. }
  514. else{
  515. elevationTag=elevationTag.toString()+'m'
  516. }
  517. }
  518. }
  519.  
  520. if (tags.includes('generation')&&typeTag=='Official'&&countryTag){
  521. genTag = getGeneration(svData,countryTag)
  522. coord.tags.push(genTag)}
  523.  
  524. if (tags.includes('year'))coord.tags.push(yearTag)
  525.  
  526. if (tags.includes('month'))coord.tags.push(yearTag.slice(-2)+'-'+monthTag)
  527.  
  528. if (tags.includes('day'))coord.tags.push(dayTag)
  529.  
  530. if (tags.includes('time')) coord.tags.push(timeTag)
  531.  
  532. if (tags.includes('time')&&timeRange) coord.tags.push(timeRange)
  533.  
  534. if (tags.includes('type'))coord.tags.push(typeTag)
  535.  
  536. if (tags.includes('type')&&trekkerTag&&typeTag=='Official')coord.tags.push('trekker')
  537.  
  538. if (tags.includes('country')&&typeTag=='Official')coord.tags.push(countryTag)
  539.  
  540. if (tags.includes('subdivision')&&typeTag=='Official')coord.tags.push(subdivisionTag)
  541.  
  542. if (tags.includes('locality')&&typeTag=='Official')coord.tags.push(localityTag)
  543.  
  544. if (tags.includes('elevation'))coord.tags.push(elevationTag)
  545. }
  546.  
  547. else {
  548. if(tags.some(tag => tagBox.includes(tag))){
  549. coord.tags.push('nopano')
  550. }
  551. }
  552.  
  553.  
  554. if (coord.tags) {coord.tags=Array.from(new Set(coord.tags))}
  555. taggedLocs.push(coord);
  556. }
  557.  
  558. async function processChunk(chunk, tags) {
  559. var service = new google.maps.StreetViewService();
  560. var promises = chunk.map(async coord => {
  561. let panoId = coord.panoId;
  562. let latLng = {lat: coord.location.lat, lng: coord.location.lng};
  563. let svData;
  564. let ccData;
  565.  
  566. if ((panoId || latLng)) {
  567. if(tags!=['country']||tags!=['elevation']){
  568. svData = await getSVData(service, panoId ? {pano: panoId} : {location: latLng, radius: 50});}
  569. }
  570. if (!panoId && (tags.includes('generation')||('country')||('elevation'))) {
  571. ccData = await UE('SingleImageSearch', coord);
  572. } else if (panoId && (tags.includes('generation')||('country')||('elevation'))) {
  573. ccData = await UE('GetMetadata', panoId);
  574. }
  575.  
  576. await processCoord(coord, tags, svData,ccData)
  577. });
  578. await Promise.all(promises);
  579.  
  580. }
  581.  
  582. function getSVData(service, options) {
  583. return new Promise(resolve => service.getPanorama({...options}, (data, status) => {
  584. resolve(data);
  585. }));
  586. }
  587.  
  588. async function processData(tags) {
  589. let successText='The JSON data has been pasted to your clipboard!';
  590. try {
  591. const totalChunks = Math.ceil(selections.length / CHUNK_SIZE);
  592. let processedChunks = 0;
  593.  
  594. const swal = Swal.fire({
  595. title: 'Tagging',
  596. text: 'If you want to tag a large number of locs by exact time or elevation, it could take quite some time. Please wait...',
  597. allowOutsideClick: false,
  598. allowEscapeKey: false,
  599. showConfirmButton: false,
  600. icon:"info",
  601. didOpen: () => {
  602. Swal.showLoading();
  603. }
  604. });
  605.  
  606. for (let i = 0; i < selections.length; i += CHUNK_SIZE) {
  607. let chunk = selections.slice(i, i + CHUNK_SIZE);
  608. await processChunk(chunk, tags);
  609. processedChunks++;
  610.  
  611. const progress = Math.min((processedChunks / totalChunks) * 100, 100);
  612. Swal.update({
  613. html: `<div>${progress.toFixed(2)}% completed</div>
  614. <div class="swal2-progress">
  615. <div class="swal2-progress-bar" role="progressbar" aria-valuenow="${progress}" aria-valuemin="0" aria-valuemax="100" style="width: ${progress}%;">
  616. </div>
  617. </div>`
  618. });
  619. }
  620.  
  621. if(exportMode){
  622. updateSelection(taggedLocs)
  623. successText='Tagging completed! Do you want to refresh the page?(The JSON data is also pasted to your clipboard)'
  624. }
  625. var newJSON=[]
  626. taggedLocs.forEach((loc)=>{
  627. newJSON.push({lat:loc.location.lat,
  628. lng:loc.location.lng,
  629. heading:loc.location.heading,
  630. pitch:loc.location.pitch,
  631. zoom:loc.location.zoom,
  632. panoId:loc.panoId,
  633. extra:{tags:loc.tags}
  634. })
  635. })
  636. GM_setClipboard(JSON.stringify(newJSON))
  637. swal.close();
  638. Swal.fire({
  639. title: 'Success!',
  640. text: successText,
  641. icon: 'success',
  642. showCancelButton: true,
  643. confirmButtonColor: '#3085d6',
  644. cancelButtonColor: '#d33',
  645. confirmButtonText: 'OK'
  646. }).then((result) => {
  647. if (result.isConfirmed) {
  648. if(exportMode){
  649. location.reload();}
  650. }
  651. });
  652. } catch (error) {
  653. swal.close();
  654. Swal.fire('Error Parsing JSON Data!', error,'error');
  655. console.error('Error processing JSON data:', error);
  656. }
  657. }
  658.  
  659. if(selections){
  660. if(selections.length>=1){processData(tags);}
  661. else{
  662. Swal.fire('Error Parsing JSON Data!', 'The input JSON data is empty! If you update the map after the page is loaded, please save it and refresh the page before tagging','error');}
  663. }else{Swal.fire('Error Parsing JSON Data!', 'The input JSON data is invaild or incorrectly formatted.','error');}
  664. }
  665.  
  666. function createCheckbox(text, tags) {
  667. var label = document.createElement('label');
  668. var checkbox = document.createElement('input');
  669. checkbox.type = 'checkbox';
  670. checkbox.value = text;
  671. checkbox.name = 'tags';
  672. checkbox.id = tags;
  673. label.appendChild(checkbox);
  674. label.appendChild(document.createTextNode(text));
  675. buttonContainer.appendChild(label);
  676. return checkbox;
  677. }
  678.  
  679. var mainButton = document.createElement('button');
  680. mainButton.textContent = 'Auto-Tag';
  681. mainButton.style.position = 'fixed';
  682. mainButton.style.right = '20px';
  683. mainButton.style.bottom = '20px';
  684. mainButton.style.borderRadius = "18px";
  685. mainButton.style.fontSize = "16px";
  686. mainButton.style.padding = "10px 20px";
  687. mainButton.style.border = "none";
  688. mainButton.style.color = "white";
  689. mainButton.style.cursor = "pointer";
  690. mainButton.style.backgroundColor = "#4CAF50";
  691. mainButton.addEventListener('click', function () {
  692. if (buttonContainer.style.display === 'none') {
  693. buttonContainer.style.display = 'block';
  694. } else {
  695. buttonContainer.style.display = 'none';
  696. }
  697. });
  698. document.body.appendChild(mainButton);
  699.  
  700. var buttonContainer = document.createElement('div');
  701. buttonContainer.style.position = 'fixed';
  702. buttonContainer.style.right = '20px';
  703. buttonContainer.style.bottom = '60px';
  704. buttonContainer.style.display = 'none';
  705. buttonContainer.style.fontSize = '16px';
  706. document.body.appendChild(buttonContainer);
  707.  
  708. var selectAllCheckbox = document.createElement('input');
  709. selectAllCheckbox.type = 'checkbox';
  710. selectAllCheckbox.id = 'selectAll';
  711. selectAllCheckbox.addEventListener('change', function () {
  712. var checkboxes = document.getElementsByName('tags');
  713. for (var i = 0; i < checkboxes.length; i++) {
  714. checkboxes[i].checked = this.checked;
  715. }
  716. });
  717. var selectAllLabel = document.createElement('label');
  718. selectAllLabel.textContent = 'Select All';
  719. selectAllLabel.htmlFor = 'selectAll';
  720.  
  721.  
  722.  
  723. var triggerButton = document.createElement('button');
  724. triggerButton.textContent = 'Star Tagging';
  725. triggerButton.addEventListener('click', function () {
  726. var checkboxes = document.getElementsByName('tags');
  727. var checkedTags = [];
  728. for (var i = 0; i < checkboxes.length; i++) {
  729. if (checkboxes[i].checked) {
  730. checkedTags.push(checkboxes[i].id);
  731. }
  732. }
  733. if (checkedTags.includes('elevation')) {
  734. Swal.fire({
  735. title: 'Set A Range For Elevation',
  736. text: 'If you select "Cancel", the script will return the exact elevation for each location.',
  737. icon: 'question',
  738. showCancelButton: true,
  739. showCloseButton: true,
  740. allowOutsideClick: false,
  741. confirmButtonColor: '#3085d6',
  742. cancelButtonColor: '#d33',
  743. confirmButtonText: 'Yes',
  744. cancelButtonText: 'Cancel'
  745. }).then((result) => {
  746. if (result.isConfirmed) {
  747. Swal.fire({
  748. title: 'Define Range for Each Segment',
  749. html: `
  750. <label> <br>Enter range for each segment, separated by commas</br></label>
  751. <textarea id="segmentRanges" class="swal2-textarea" placeholder="such as:-1-10,11-35"></textarea>
  752. `,
  753. icon: 'question',
  754. showCancelButton: true,
  755. showCloseButton: true,
  756. allowOutsideClick: false,
  757. focusConfirm: false,
  758. preConfirm: () => {
  759. const segmentRangesInput = document.getElementById('segmentRanges').value.trim();
  760. if (!segmentRangesInput) {
  761. Swal.showValidationMessage('Please enter range for each segment');
  762. return false;
  763. }
  764. const segmentRanges = segmentRangesInput.split(',');
  765. const validatedRanges = segmentRanges.map(range => {
  766. const matches = range.trim().match(/^\s*(-?\d+)\s*-\s*(-?\d+)\s*$/);
  767. if (matches) {
  768. const min = Number(matches[1]);
  769. const max = Number(matches[2]);
  770. return { min, max };
  771. } else {
  772. Swal.showValidationMessage('Invalid range format. Please use format: minValue-maxValue');
  773. return false;
  774. }
  775. });
  776. return validatedRanges.filter(Boolean);
  777. },
  778. confirmButtonColor: '#3085d6',
  779. cancelButtonColor: '#d33',
  780. confirmButtonText: 'Yes',
  781. cancelButtonText: 'Cancel',
  782. inputValidator: (value) => {
  783. if (!value.trim()) {
  784. return 'Please enter range for each segment';
  785. }
  786. }
  787. }).then((result) => {
  788. if (result.isConfirmed) {
  789. runScript(checkedTags, result.value)
  790. } else {
  791. Swal.showValidationMessage('You canceled input');
  792. }
  793. });
  794. }
  795. else if (result.dismiss === Swal.DismissReason.cancel) {
  796. runScript(checkedTags)
  797. }
  798. });
  799. }
  800. else {
  801. runScript(checkedTags)
  802. }
  803. })
  804. buttonContainer.appendChild(triggerButton);
  805. buttonContainer.appendChild(selectAllCheckbox);
  806. buttonContainer.appendChild(selectAllLabel);
  807. tagBox.forEach(tag => {
  808. createCheckbox(tag, tag.toLowerCase());
  809. });
  810.  
  811. })();