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