Geoguessr Map-Making Auto-Tag

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

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

  1. // ==UserScript==
  2. // @name Geoguessr Map-Making Auto-Tag
  3. // @namespace https://www.geoguessr.com/user/6494f9bbab07ca3ea843220f
  4. // @version 3.84.4
  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.  
  207. if (option) {
  208. exportMode='save'
  209. }
  210. else if(!selections&&inputDismiss==='cancel'){
  211. exportMode=null
  212. }
  213. else{
  214. return
  215. }
  216. const selectedLocs=await getSelection()
  217. mapData=await getMap()
  218. selections=await matchSelection(selectedLocs,mapData)
  219.  
  220. async function UE(t, e, s, d) {
  221. try {
  222. const r = `https://maps.googleapis.com/$rpc/google.internal.maps.mapsjs.v1.MapsJsInternalService/${t}`;
  223. let payload = createPayload(t, e,s,d);
  224.  
  225. const response = await fetch(r, {
  226. method: "POST",
  227. headers: {
  228. "content-type": "application/json+protobuf",
  229. "x-user-agent": "grpc-web-javascript/0.1"
  230. },
  231. body: payload,
  232. mode: "cors",
  233. credentials: "omit"
  234. });
  235.  
  236. if (!response.ok) {
  237. throw new Error(`HTTP error! status: ${response.status}`);
  238. } else {
  239. return await response.json();
  240. }
  241. } catch (error) {
  242. console.error(`There was a problem with the UE function: ${error.message}`);
  243. }
  244. }
  245.  
  246. function createPayload(mode,coorData,s,d) {
  247. let payload;
  248.  
  249. if (mode === 'GetMetadata') {
  250. payload = [["apiv3",null,null,null,"US",null,null,null,null,null,[[0]]],["en","US"],[[[2,coorData]]],[[1,2,3,4,8,6]]];
  251. } else if (mode === 'SingleImageSearch') {
  252. var lat = coorData.location.lat;
  253. var lng = coorData.location.lng;
  254. lat = lat % 1 !== 0 && lat.toString().split('.')[1].length >6 ? parseFloat(lat.toFixed(6)) : lat;
  255. lng = lng % 1 !== 0 && lng.toString().split('.')[1].length > 6 ? parseFloat(lng.toFixed(6)) : lng;
  256. if(s&&d){
  257. 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]]]
  258. }else{
  259. payload =[["apiv3",null,null,null,"US",null,null,null,null,null, [[0]]],
  260. [[null,null,lat,lng],50],
  261. [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]]];}
  262. } else {
  263. throw new Error("Invalid mode!");
  264. }
  265. return JSON.stringify(payload);
  266. }
  267.  
  268. function monthToTimestamp(m) {
  269.  
  270. const [year, month] = m.split('-');
  271.  
  272. const startDate =Math.round( new Date(year, month-1,1).getTime()/1000);
  273.  
  274. const endDate =Math.round( new Date(year, month, 1).getTime()/1000)-1;
  275.  
  276. return { startDate, endDate };
  277. }
  278.  
  279. async function binarySearch(c, start,end) {
  280. let capture
  281. let response
  282. while (end - start >= accuracy) {
  283. let mid= Math.round((start + end) / 2);
  284. response = await UE("SingleImageSearch", c, start,end);
  285. if (response&&response[0][2]== "Search returned no images." ){
  286. start=mid+start-end
  287. end=start-mid+end
  288. mid=Math.round((start+end)/2)
  289. } else {
  290. start=mid
  291. mid=Math.round((start+end)/2)
  292. }
  293. capture=mid
  294. }
  295.  
  296. return capture
  297. }
  298.  
  299. function getMetaData(svData) {
  300. if (svData) {
  301. let floors=svData.KF
  302. let floor;
  303. let year = 'noyear',month = 'nomonth'
  304. let panoType='Unofficial'
  305. let subdivision='nosub',locality='nolocality'
  306. if (svData.imageDate) {
  307. const matchYear = svData.imageDate.match(/\d{4}/);
  308. if (matchYear) {
  309. year = matchYear[0];
  310. }
  311.  
  312. const matchMonth = svData.imageDate.match(/-(\d{2})/);
  313. if (matchMonth) {
  314. month = matchMonth[1];
  315. }
  316. }
  317.  
  318. if (floors){
  319. const targetBx=svData.Bx
  320. for (let i = 0; i < floors.length; i++) {
  321. if (floors[i].Bx === targetBx) {
  322. floor=floors[i].description;
  323. }
  324. }
  325.  
  326.  
  327. }
  328. if (svData.copyright.includes('Google')) {
  329. panoType = 'Official';
  330. }
  331.  
  332. if(svData.location.description){
  333. let parts = svData.location.description.split(',');
  334. if(parts.length > 1){
  335. subdivision = parts[parts.length-1].trim();
  336. locality = parts[parts.length-2].trim();
  337. } else {
  338. subdivision = svData.location.description;
  339.  
  340. }
  341. }
  342. return [year,month,panoType,subdivision,locality,floor]
  343. }
  344. else{
  345. return null
  346. }
  347. }
  348.  
  349. function getGeneration(svData,country) {
  350. if (svData&&svData.tiles) {
  351. if (svData.tiles.worldSize.height === 1664) { // Gen 1
  352. return 'Gen1';
  353. } else if (svData.tiles.worldSize.height === 6656) { // Gen 2 or 3
  354.  
  355. let lat;
  356. for (let key in svData.Sv) {
  357. lat = svData.Sv[key].lat;
  358. break;
  359. }
  360.  
  361. let date;
  362. if (svData.imageDate) {
  363. date = new Date(svData.imageDate);
  364. } else {
  365. date = 'nodata';
  366. }
  367.  
  368. if (date!=='nodata'&&((country === 'BD' && (date >= new Date('2021-04'))) ||
  369. (country === 'EC' && (date >= new Date('2022-03'))) ||
  370. (country === 'FI' && (date >= new Date('2020-09'))) ||
  371. (country === 'IN' && (date >= new Date('2021-10'))) ||
  372. (country === 'LK' && (date >= new Date('2021-02'))) ||
  373. (country === 'KH' && (date >= new Date('2022-10'))) ||
  374. (country === 'LB' && (date >= new Date('2021-05'))) ||
  375. (country === 'NG' && (date >= new Date('2021-06'))) ||
  376. (country === 'ST') ||
  377. (country === 'US' && lat > 52 && (date >= new Date('2019-01'))))) {
  378. return 'Shitcam';
  379. }
  380.  
  381. let gen2Countries = ['AU', 'BR', 'CA', 'CL', 'JP', 'GB', 'IE', 'NZ', 'MX', 'RU', 'US', 'IT', 'DK', 'GR', 'RO',
  382. 'PL', 'CZ', 'CH', 'SE', 'FI', 'BE', 'LU', 'NL', 'ZA', 'SG', 'TW', 'HK', 'MO', 'MC', 'SM',
  383. 'AD', 'IM', 'JE', 'FR', 'DE', 'ES', 'PT'];
  384. if (gen2Countries.includes(country)) {
  385.  
  386. return 'Gen2or3';
  387. }
  388. else{
  389. return 'Gen3';}
  390. }
  391. else if(svData.tiles.worldSize.height === 8192){
  392. return 'Gen4';
  393. }
  394. }
  395. return 'Unknown';
  396. }
  397.  
  398. async function getLocal(coord, timestamp) {
  399. const apiUrl = "https://api.geotimezone.com/public/timezone?";
  400. const systemTimezoneOffset = -new Date().getTimezoneOffset() * 60;
  401.  
  402. try {
  403. const [lat, lng] = coord;
  404. const url = `${apiUrl}latitude=${lat}&longitude=${lng}`;
  405.  
  406. const responsePromise = new Promise((resolve, reject) => {
  407. GM_xmlhttpRequest({
  408. method: "GET",
  409. url: url,
  410. responseType: "json",
  411. onload: function(response) {
  412. if (response.status >= 200 && response.status < 300) {
  413. resolve(response.response);
  414. } else {
  415. Swal.fire('Error fecthing exact time!', "Request failed: " + response.statusText,'error')
  416. reject(new Error("Request failed: " + response.statusText));
  417. }
  418. },
  419. onerror: function(error) {
  420. reject(new Error("There was a network error: " + error));
  421. }
  422. });
  423. });
  424.  
  425. function extractOffset(text) {
  426. const regex = /UTC[+-]?\d+/;
  427. const match = text.match(regex);
  428. if (match) {
  429. return parseInt(match[0].substring(3));
  430. } else {
  431. return null;
  432. }
  433. }
  434. const data = await responsePromise;
  435. const offset = extractOffset(data.offset);
  436. const targetTimezoneOffset = offset * 3600;
  437. const offsetDiff = systemTimezoneOffset - targetTimezoneOffset;
  438. const convertedTimestamp = Math.round(timestamp - offsetDiff);
  439. return convertedTimestamp;
  440. } catch (error) {
  441. throw error;
  442. }
  443. }
  444.  
  445. var CHUNK_SIZE = 1200;
  446. if (tags.includes('time')){
  447. CHUNK_SIZE = 500
  448. }
  449. var promises = [];
  450.  
  451. async function processCoord(coord, tags, svData,ccData) {
  452. if (svData||ccData){
  453. let meta=getMetaData(svData)
  454. let yearTag=meta[0]
  455. let monthTag=meta[1]
  456. let typeTag=meta[2]
  457. let subdivisionTag=meta[3]
  458. let localityTag=meta[4]
  459. let floorTag=meta[5]
  460. let countryTag,elevationTag
  461. let genTag,trekkerTag
  462. let dayTag,timeTag,exactTime,timeRange
  463. var date=monthToTimestamp(meta[0]+'-'+meta[1])
  464.  
  465. if(tags.includes('day')||tags.includes('time')){
  466. exactTime=await binarySearch(coord, date.startDate,date.endDate)
  467. if (exactTime<=date.startDate||exactTime>=date.endDate){
  468. exactTime=null
  469. }
  470. }
  471.  
  472. if(!exactTime){dayTag='noday'
  473. timeTag='notime'
  474. }
  475. else{
  476.  
  477. const currentDate = new Date();
  478. const currentOffset =-(currentDate.getTimezoneOffset())*60
  479. const dayOffset = currentOffset-Math.round((coord.location.lng / 15) * 3600);
  480. const LocalDay=new Date(Math.round(exactTime-dayOffset)*1000)
  481. dayTag = LocalDay.toISOString().split('T')[0];
  482.  
  483. if(tags.includes('time')) {
  484.  
  485. var localTime=await getLocal([coord.location.lat,coord.location.lng],exactTime)
  486. var timeObject=new Date(localTime*1000)
  487. timeTag =`${timeObject.getHours().toString().padStart(2, '0')}:${timeObject.getMinutes().toString().padStart(2, '0')}:${timeObject.getSeconds().toString().padStart(2, '0')}`;
  488. var hour = timeObject.getHours();
  489.  
  490. if (hour < 11) {
  491. timeRange = 'Morning';
  492. } else if (hour >= 11 && hour < 13) {
  493. timeRange = 'Noon';
  494. } else if (hour >= 13 && hour < 17) {
  495. timeRange = 'Afternoon';
  496. } else if(hour >= 17 && hour < 19) {
  497. timeRange = 'Evening';
  498. }
  499. else{
  500. timeRange = 'Night';
  501. }
  502. }
  503. }
  504. if (ccData){
  505. try {
  506. countryTag = ccData[1][0][5][0][1][4]
  507. elevationTag=ccData[1][0][5][0][1][1][0]
  508. trekkerTag=ccData[1][0][6][5].toString()
  509. }
  510. catch (error) {
  511. try {
  512. countryTag = ccData[1][5][0][1][4]
  513. elevationTag=ccData[1][5][0][1][1][0]
  514. trekkerTag=ccData[1][6][5].toString()
  515. } catch (error) {
  516. return
  517. }
  518. }
  519. if (!countryTag)countryTag='nocountry'
  520.  
  521. if( trekkerTag.includes('scout')){
  522. trekkerTag='trekker'
  523. }
  524. else{trekkerTag=null}
  525.  
  526. if (!elevationTag)elevationTag='noelevation'
  527. else{
  528. elevationTag=Math.round(elevationTag*100)/100
  529. if(sR){
  530. elevationTag=findRange(elevationTag,sR)
  531. }
  532. else{
  533. elevationTag=elevationTag.toString()+'m'
  534. }
  535. }
  536. }
  537.  
  538. if (tags.includes('generation')&&typeTag=='Official'&&countryTag){
  539. genTag = getGeneration(svData,countryTag)
  540. coord.tags.push(genTag)}
  541.  
  542. if (tags.includes('year'))coord.tags.push(yearTag)
  543.  
  544. if (tags.includes('month'))coord.tags.push(yearTag.slice(-2)+'-'+monthTag)
  545.  
  546. if (tags.includes('day'))coord.tags.push(dayTag)
  547.  
  548. if (tags.includes('time')) coord.tags.push(timeTag)
  549.  
  550. if (tags.includes('time')&&timeRange) coord.tags.push(timeRange)
  551.  
  552. if (tags.includes('type'))coord.tags.push(typeTag)
  553.  
  554. if (tags.includes('type')&&trekkerTag&&typeTag=='Official')coord.tags.push('trekker')
  555.  
  556. if (tags.includes('type')&&floorTag&&typeTag=='Official')coord.tags.push(floorTag)
  557.  
  558. if (tags.includes('country')&&typeTag=='Official')coord.tags.push(countryTag)
  559.  
  560. if (tags.includes('subdivision')&&typeTag=='Official')coord.tags.push(subdivisionTag)
  561.  
  562. if (tags.includes('locality')&&typeTag=='Official')coord.tags.push(localityTag)
  563.  
  564. if (tags.includes('elevation'))coord.tags.push(elevationTag)
  565. }
  566. else {
  567. if(tags.some(tag => tagBox.includes(tag))){
  568. coord.tags.push('nopano')
  569. }
  570. }
  571.  
  572.  
  573. if (coord.tags) {coord.tags=Array.from(new Set(coord.tags))}
  574. taggedLocs.push(coord);
  575. }
  576.  
  577. async function processChunk(chunk, tags) {
  578. var service = new google.maps.StreetViewService();
  579. var promises = chunk.map(async coord => {
  580. let panoId = coord.panoId;
  581. let latLng = {lat: coord.location.lat, lng: coord.location.lng};
  582. let svData;
  583. let ccData;
  584.  
  585. if ((panoId || latLng)) {
  586. if(tags!=['country']&&tags!=['elevation']){
  587. svData = await getSVData(service, panoId ? {pano: panoId} : {location: latLng, radius: 50});}
  588. }
  589. if (!panoId && (tags.includes('generation')||('country')||('elevation')||('type'))) {
  590. ccData = await UE('SingleImageSearch', coord);
  591. } else if (panoId && (tags.includes('generation')||('country')||('elevation')||('type'))) {
  592. ccData = await UE('GetMetadata', panoId);
  593. }
  594.  
  595. await processCoord(coord, tags, svData,ccData)
  596. });
  597. await Promise.all(promises);
  598.  
  599. }
  600.  
  601. function getSVData(service, options) {
  602. return new Promise(resolve => service.getPanorama({...options}, (data, status) => {
  603. resolve(data);
  604. }));
  605. }
  606.  
  607. async function processData(tags) {
  608. let successText='The JSON data has been pasted to your clipboard!';
  609. try {
  610. const totalChunks = Math.ceil(selections.length / CHUNK_SIZE);
  611. let processedChunks = 0;
  612.  
  613. const swal = Swal.fire({
  614. title: 'Tagging',
  615. text: 'If you want to tag a large number of locs by exact time or elevation, it could take quite some time. Please wait...',
  616. allowOutsideClick: false,
  617. allowEscapeKey: false,
  618. showConfirmButton: false,
  619. icon:"info",
  620. didOpen: () => {
  621. Swal.showLoading();
  622. }
  623. });
  624.  
  625. for (let i = 0; i < selections.length; i += CHUNK_SIZE) {
  626. let chunk = selections.slice(i, i + CHUNK_SIZE);
  627. await processChunk(chunk, tags);
  628. processedChunks++;
  629.  
  630. const progress = Math.min((processedChunks / totalChunks) * 100, 100);
  631. Swal.update({
  632. html: `<div>${progress.toFixed(2)}% completed</div>
  633. <div class="swal2-progress">
  634. <div class="swal2-progress-bar" role="progressbar" aria-valuenow="${progress}" aria-valuemin="0" aria-valuemax="100" style="width: ${progress}%;">
  635. </div>
  636. </div>`
  637. });
  638. }
  639.  
  640. if(exportMode){
  641. updateSelection(taggedLocs)
  642. successText='Tagging completed! Do you want to refresh the page?(The JSON data is also pasted to your clipboard)'
  643. }
  644. var newJSON=[]
  645. taggedLocs.forEach((loc)=>{
  646. newJSON.push({lat:loc.location.lat,
  647. lng:loc.location.lng,
  648. heading:loc.location.heading,
  649. pitch:loc.location.pitch,
  650. zoom:loc.location.zoom,
  651. panoId:loc.panoId,
  652. extra:{tags:loc.tags}
  653. })
  654. })
  655. GM_setClipboard(JSON.stringify(newJSON))
  656. swal.close();
  657. Swal.fire({
  658. title: 'Success!',
  659. text: successText,
  660. icon: 'success',
  661. showCancelButton: true,
  662. confirmButtonColor: '#3085d6',
  663. cancelButtonColor: '#d33',
  664. confirmButtonText: 'OK'
  665. }).then((result) => {
  666. if (result.isConfirmed) {
  667. if(exportMode){
  668. location.reload();}
  669. }
  670. });
  671. } catch (error) {
  672. swal.close();
  673. Swal.fire('Error Tagging!', error,'error');
  674. console.error('Error processing JSON data:', error);
  675. }
  676. }
  677.  
  678. if(selections){
  679. if(selections.length>=1){processData(tags);}
  680. else{
  681. 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');}
  682. }else{Swal.fire('Error Parsing JSON Data!', 'The input JSON data is invaild or incorrectly formatted.','error');}
  683. }
  684.  
  685. function createCheckbox(text, tags) {
  686. var label = document.createElement('label');
  687. var checkbox = document.createElement('input');
  688. checkbox.type = 'checkbox';
  689. checkbox.value = text;
  690. checkbox.name = 'tags';
  691. checkbox.id = tags;
  692. label.appendChild(checkbox);
  693. label.appendChild(document.createTextNode(text));
  694. buttonContainer.appendChild(label);
  695. return checkbox;
  696. }
  697.  
  698. var mainButton = document.createElement('button');
  699. mainButton.textContent = 'Auto-Tag';
  700. mainButton.style.position = 'fixed';
  701. mainButton.style.right = '20px';
  702. mainButton.style.bottom = '20px';
  703. mainButton.style.borderRadius = "18px";
  704. mainButton.style.fontSize = "16px";
  705. mainButton.style.padding = "10px 20px";
  706. mainButton.style.border = "none";
  707. mainButton.style.color = "white";
  708. mainButton.style.cursor = "pointer";
  709. mainButton.style.backgroundColor = "#4CAF50";
  710. mainButton.addEventListener('click', function () {
  711. if (buttonContainer.style.display === 'none') {
  712. buttonContainer.style.display = 'block';
  713. } else {
  714. buttonContainer.style.display = 'none';
  715. }
  716. });
  717. document.body.appendChild(mainButton);
  718.  
  719. var buttonContainer = document.createElement('div');
  720. buttonContainer.style.position = 'fixed';
  721. buttonContainer.style.right = '20px';
  722. buttonContainer.style.bottom = '60px';
  723. buttonContainer.style.display = 'none';
  724. buttonContainer.style.fontSize = '16px';
  725. document.body.appendChild(buttonContainer);
  726.  
  727. var selectAllCheckbox = document.createElement('input');
  728. selectAllCheckbox.type = 'checkbox';
  729. selectAllCheckbox.id = 'selectAll';
  730. selectAllCheckbox.addEventListener('change', function () {
  731. var checkboxes = document.getElementsByName('tags');
  732. for (var i = 0; i < checkboxes.length; i++) {
  733. checkboxes[i].checked = this.checked;
  734. }
  735. });
  736. var selectAllLabel = document.createElement('label');
  737. selectAllLabel.textContent = 'Select All';
  738. selectAllLabel.htmlFor = 'selectAll';
  739.  
  740.  
  741.  
  742. var triggerButton = document.createElement('button');
  743. triggerButton.textContent = 'Star Tagging';
  744. triggerButton.addEventListener('click', function () {
  745. var checkboxes = document.getElementsByName('tags');
  746. var checkedTags = [];
  747. for (var i = 0; i < checkboxes.length; i++) {
  748. if (checkboxes[i].checked) {
  749. checkedTags.push(checkboxes[i].id);
  750. }
  751. }
  752. if (checkedTags.includes('elevation')) {
  753. Swal.fire({
  754. title: 'Set A Range For Elevation',
  755. text: 'If you select "Cancel", the script will return the exact elevation for each location.',
  756. icon: 'question',
  757. showCancelButton: true,
  758. showCloseButton: true,
  759. allowOutsideClick: false,
  760. confirmButtonColor: '#3085d6',
  761. cancelButtonColor: '#d33',
  762. confirmButtonText: 'Yes',
  763. cancelButtonText: 'Cancel'
  764. }).then((result) => {
  765. if (result.isConfirmed) {
  766. Swal.fire({
  767. title: 'Define Range for Each Segment',
  768. html: `
  769. <label> <br>Enter range for each segment, separated by commas</br></label>
  770. <textarea id="segmentRanges" class="swal2-textarea" placeholder="such as:-1-10,11-35"></textarea>
  771. `,
  772. icon: 'question',
  773. showCancelButton: true,
  774. showCloseButton: true,
  775. allowOutsideClick: false,
  776. focusConfirm: false,
  777. preConfirm: () => {
  778. const segmentRangesInput = document.getElementById('segmentRanges').value.trim();
  779. if (!segmentRangesInput) {
  780. Swal.showValidationMessage('Please enter range for each segment');
  781. return false;
  782. }
  783. const segmentRanges = segmentRangesInput.split(',');
  784. const validatedRanges = segmentRanges.map(range => {
  785. const matches = range.trim().match(/^\s*(-?\d+)\s*-\s*(-?\d+)\s*$/);
  786. if (matches) {
  787. const min = Number(matches[1]);
  788. const max = Number(matches[2]);
  789. return { min, max };
  790. } else {
  791. Swal.showValidationMessage('Invalid range format. Please use format: minValue-maxValue');
  792. return false;
  793. }
  794. });
  795. return validatedRanges.filter(Boolean);
  796. },
  797. confirmButtonColor: '#3085d6',
  798. cancelButtonColor: '#d33',
  799. confirmButtonText: 'Yes',
  800. cancelButtonText: 'Cancel',
  801. inputValidator: (value) => {
  802. if (!value.trim()) {
  803. return 'Please enter range for each segment';
  804. }
  805. }
  806. }).then((result) => {
  807. if (result.isConfirmed) {
  808. runScript(checkedTags, result.value)
  809. } else {
  810. Swal.showValidationMessage('You canceled input');
  811. }
  812. });
  813. }
  814. else if (result.dismiss === Swal.DismissReason.cancel) {
  815. runScript(checkedTags)
  816. }
  817. });
  818. }
  819. else {
  820. runScript(checkedTags)
  821. }
  822. })
  823. buttonContainer.appendChild(triggerButton);
  824. buttonContainer.appendChild(selectAllCheckbox);
  825. buttonContainer.appendChild(selectAllLabel);
  826. tagBox.forEach(tag => {
  827. createCheckbox(tag, tag.toLowerCase());
  828. });
  829.  
  830. })();