Geoguessr Map-Making Auto-Tag

Tag your panos by date, exactTime, address, generation, elevation

目前为 2024-08-18 提交的版本,查看 最新版本

  1. // ==UserScript==
  2. // @name Geoguessr Map-Making Auto-Tag
  3. // @namespace https://greasyfork.org/users/1179204
  4. // @version 3.87.5
  5. // @description Tag your panos by date, exactTime, address, generation, elevation
  6. // @author KaKa
  7. // @match *://map-making.app/maps/*
  8. // @grant GM_setClipboard
  9. // @grant GM_xmlhttpRequest
  10. // @require https://cdn.jsdelivr.net/npm/sweetalert2@11
  11. // @require https://cdnjs.cloudflare.com/ajax/libs/suncalc/1.9.0/suncalc.min.js
  12. // @require https://cdn.jsdelivr.net/npm/browser-geo-tz@0.1.0/dist/geotz.min.js
  13. // @license BSD
  14. // @icon https://www.svgrepo.com/show/423677/tag-price-label.svg
  15. // ==/UserScript==
  16.  
  17. (function() {
  18. 'use strict';
  19. let accuracy=60 /* You could modifiy accuracy here, default setting is 60s */
  20.  
  21. let tagBox = ['Year', 'Month','Day', 'Time','Sun','Weather','Type','Country', 'Subdivision', 'Generation', 'Elevation','Driving Direction','Reset Heading','Update','Detect','Fix']
  22.  
  23. let months = ['January', 'February', 'March', 'April', 'May', 'June','July', 'August', 'September', 'October', 'November', 'December'];
  24.  
  25. let tooltips = {
  26. 'Year': 'Year of pano capture in format yyyy',
  27. 'Month': 'Month of pano capture in format yy-mm',
  28. 'Day': 'Specific date of pano capture in format yyyy-mm-dd',
  29. 'Time': 'Exact time of pano capture with optional time range description, e.g., 09:35:21 marked as Morning',
  30. 'Country': 'Country of pano capture location (Google data)',
  31. 'Subdivision': 'Primary administrative subdivision of street view location',
  32. 'Generation': 'Camera generation of the street view, categorized as Gen1, Gen2orGen3, Gen3, Gen4, Shitcam',
  33. 'Elevation': 'Elevation of street view location (Google data)',
  34. 'Type': 'Type of pano, categorized as Official, Unofficial, Trekker (may include floor ID if available)',
  35. 'Driving Direction': 'Absolute driving direction of street view vehicle',
  36. 'Reset Heading': 'Reset heading to default driving direction of street view vehicle',
  37. 'Fix': 'Fix broken locs by updating to latest coverage or searching for specific coverage based on saved date from map-making',
  38. 'Update': 'Update pano to latest coverage or based on saved date from map-making, effective only for locs with panoID',
  39. 'Detect': 'Detect pano that is about to be removed and mark it as "Dangerous" ',
  40. 'Sun':'Detect whether it is sunset or sunrise coverage',
  41. 'Weather':'Weather type recorded by the weather station closest to the loc, with a accuracy of 10mins(effective only for defalut coverage)'
  42. };
  43.  
  44. let weatherCache={}
  45.  
  46. const weatherCodeMap = {
  47. 0: 'Clear sky',
  48. 1: 'Mainly clear',
  49. 2: 'Partly cloudy',
  50. 3: 'Mostly cloudy',
  51. 4: 'Overcast',
  52. 5: 'Light rain showers',
  53. 6: 'Moderate rain showers',
  54. 7: 'Heavy rain showers',
  55. 8: 'Light snow showers',
  56. 9: 'Heavy snow showers',
  57. 10: 'Rain and snow showers',
  58. 11: 'Thunderstorm',
  59. 12: 'Fog',
  60. 13: 'Light rain',
  61. 14: 'Moderate rain',
  62. 15: 'Heavy rain',
  63. 16: 'Light snow',
  64. 17: 'Moderate snow',
  65. 18: 'Heavy snow',
  66. 19: 'Freezing rain',
  67. 20: 'Freezing snow'};
  68.  
  69. function deepClone(obj) {
  70. if (obj === null || typeof obj !== 'object') {
  71. return obj;
  72. }
  73.  
  74. const datePattern = /^(\d{4}-\d{2}-\d{2}T\d{2}:\d{2}:\d{2}([.,]\d{1,3})?Z?)$/;
  75.  
  76. if (Array.isArray(obj)) {
  77. return obj.map(item => deepClone(item));
  78. }
  79.  
  80. if (obj instanceof Date) {
  81. return new Date(obj.getTime());
  82. }
  83.  
  84. if (typeof obj === 'object') {
  85. const clonedObj = {};
  86. for (const key in obj) {
  87. if (obj.hasOwnProperty(key)) {
  88. if (typeof obj[key] === 'string' && datePattern.test(obj[key])) {
  89. clonedObj[key] = new Date(obj[key]);
  90. } else {
  91. clonedObj[key] = deepClone(obj[key]);
  92. }
  93. }
  94. }
  95. return clonedObj;
  96. }
  97.  
  98. return obj;
  99. }
  100.  
  101. function updateLocation(o,n) {
  102. const editor=unsafeWindow.editor
  103. if (editor){
  104. editor.removeLocations(o)
  105. editor.importLocations(n)
  106. }
  107. }
  108.  
  109. function findRange(elevation, ranges) {
  110. for (let i = 0; i < ranges.length; i++) {
  111. const range = ranges[i];
  112. if (elevation >= range.min && elevation <= range.max) {
  113. return `${range.min}-${range.max}m`;
  114. }
  115. }
  116. if (!elevation) {
  117. return 'noElevation';
  118. }
  119. return `${JSON.stringify(elevation)}m`;
  120. }
  121.  
  122. async function runScript(tags,sR) {
  123. let taggedLocs=[]
  124. let exportMode,selections,fixStrategy
  125.  
  126. if (tags.length<1){
  127. swal.fire('Feature not found!', 'Please select at least one feature!','warning')
  128. return}
  129. if (tags.includes('fix')){
  130. const { value: fixOption,dismiss: fixDismiss } = await Swal.fire({
  131. title:'Fix Strategy',
  132. icon:'question',
  133. text: 'Would you like to fix the location based on the map-making data. (more suitable for those locs with a specific date coverage) Else it will update the broken loc with recent coverage.',
  134. showCancelButton: true,
  135. showCloseButton:true,
  136. allowOutsideClick: false,
  137. confirmButtonColor: '#3085d6',
  138. cancelButtonColor: '#d33',
  139. confirmButtonText: 'Yes',
  140. cancelButtonText: 'No',
  141.  
  142. })
  143. if(fixOption)fixStrategy='exactly'
  144. else if(!fixOption&&fixDismiss==='cancel'){
  145. fixStrategy=null
  146. }
  147. else{
  148. return
  149. }
  150. };
  151.  
  152. const { value: option, dismiss: inputDismiss } = await Swal.fire({
  153. title: 'Export',
  154. 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.',
  155. icon: 'question',
  156. showCancelButton: true,
  157. showCloseButton: true,
  158. allowOutsideClick: false,
  159. confirmButtonColor: '#3085d6',
  160. cancelButtonColor: '#d33',
  161. confirmButtonText: 'Yes',
  162. cancelButtonText: 'Cancel'
  163. });
  164.  
  165. if (option) {
  166. exportMode = 'save'
  167. }
  168. else if (!selections && inputDismiss === 'cancel') {
  169. exportMode = false
  170. }
  171. else {
  172. return
  173. }
  174.  
  175. selections=getSelection()
  176.  
  177. if (!selections||selections.length<1){
  178. swal.fire('Selection not found!', 'Please select at least one location as selection!','warning')
  179. return
  180. }
  181.  
  182. var CHUNK_SIZE = 1200;
  183. if (tags.includes('time')){
  184. CHUNK_SIZE = 1000
  185. }
  186. var promises = [];
  187.  
  188. if(selections){
  189. if(selections.length>=1){processData(tags);}
  190. else{
  191. 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');}
  192. }else{Swal.fire('Error Parsing JSON Data!', 'The input JSON data is invaild or incorrectly formatted.','error');}
  193.  
  194. async function UE(t, e, s, d) {
  195. try {
  196. const r = `https://maps.googleapis.com/$rpc/google.internal.maps.mapsjs.v1.MapsJsInternalService/${t}`;
  197. let payload = createPayload(t, e,s,d);
  198.  
  199. const response = await fetch(r, {
  200. method: "POST",
  201. headers: {
  202. "content-type": "application/json+protobuf",
  203. "x-user-agent": "grpc-web-javascript/0.1"
  204. },
  205. body: payload,
  206. mode: "cors",
  207. credentials: "omit"
  208. });
  209.  
  210. if (!response.ok) {
  211. throw new Error(`HTTP error! status: ${response.status}`);
  212. } else {
  213. return await response.json();
  214. }
  215. } catch (error) {
  216. console.error(`There was a problem with the UE function: ${error.message}`);
  217. }
  218. }
  219.  
  220. function createPayload(mode,coorData,s,d,r) {
  221. let payload;
  222. if(!r)r=50 // default search radius
  223. if (mode === 'GetMetadata') {
  224. payload = [["apiv3",null,null,null,"US",null,null,null,null,null,[[0]]],["en","US"],[[[2,coorData]]],[[1,2,3,4,8,6]]];
  225. } else if (mode === 'SingleImageSearch') {
  226. var lat = coorData.lat;
  227. var lng = coorData.lng;
  228. lat = lat % 1 !== 0 && lat.toString().split('.')[1].length >6 ? parseFloat(lat.toFixed(6)) : lat;
  229. lng = lng % 1 !== 0 && lng.toString().split('.')[1].length > 6 ? parseFloat(lng.toFixed(6)) : lng;
  230. if(s&&d){
  231. payload=[["apiv3"],[[null,null,lat,lng],r],[[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]]]
  232. }else{
  233. payload =[["apiv3"],
  234. [[null,null,lat,lng],r],
  235. [null,["en","US"],null,null,null,null,null,null,[2],null,[[[2,true,2]]]], [[1,2,3,4,8,6]]];}
  236. } else {
  237. throw new Error("Invalid mode!");
  238. }
  239. return JSON.stringify(payload);
  240. }
  241.  
  242. function monthToTimestamp(m) {
  243.  
  244. const [year, month] = m.split('-');
  245.  
  246. const startDate =Math.round( new Date(year, month-1,1).getTime()/1000);
  247.  
  248. const endDate =Math.round( new Date(year, month, 1).getTime()/1000)-1;
  249.  
  250. return { startDate, endDate };
  251. }
  252.  
  253. async function binarySearch(c, start,end) {
  254. let capture
  255. let response
  256. while (end - start >= accuracy) {
  257. let mid= Math.round((start + end) / 2);
  258. response = await UE("SingleImageSearch", c, start,end,10);
  259. if (response&&response[0][2]== "Search returned no images." ){
  260. start=mid+start-end
  261. end=start-mid+end
  262. mid=Math.round((start+end)/2)
  263. } else {
  264. start=mid
  265. mid=Math.round((start+end)/2)
  266. }
  267. capture=mid
  268. }
  269.  
  270. return capture
  271. }
  272.  
  273. function getMetaData(svData) {
  274. let year = 'Year not found',month = 'Month not found'
  275. let panoType='unofficial'
  276. let subdivision='Subdivision not found'
  277. let defaultHeading=null
  278. if (svData) {
  279. if (svData.imageDate) {
  280. const matchYear = svData.imageDate.match(/\d{4}/);
  281. if (matchYear) {
  282. year = matchYear[0];
  283. }
  284.  
  285. const matchMonth = svData.imageDate.match(/-(\d{2})/);
  286. if (matchMonth) {
  287. month = matchMonth[1];
  288. }
  289. }
  290. if (svData.copyright.includes('Google')) {
  291. panoType = 'Official';
  292. }
  293. if (svData.tiles&&svData.tiles&&svData.tiles.originHeading){
  294. defaultHeading=svData.tiles.originHeading
  295. }
  296. if(svData.location.description){
  297. let parts = svData.location.description.split(',');
  298. if(parts.length > 1){
  299. subdivision = parts[parts.length-1].trim();
  300. } else {
  301. subdivision = svData.location.description;
  302. }
  303. }
  304. return [year,month,panoType,subdivision,defaultHeading]
  305. }
  306. else{
  307. return null
  308. }
  309. }
  310.  
  311. function extractDate(array) {
  312. let year, month;
  313.  
  314. array.forEach(element => {
  315. const yearRegex1 = /^(\d{2})-(\d{2})$/; // Matches yy-mm
  316. const yearRegex2 = /^(\d{4})-(\d{2})$/; // Matches yyyy-mm
  317. const yearRegex3 = /^(\d{4})$/; // Matches yyyy
  318. const monthRegex1 = /^(\d{2})$/; // Matches mm
  319. const monthRegex2 = /^(January|February|March|April|May|June|July|August|September|October|November|December)$/i; // Matches month names
  320.  
  321. if (!month && yearRegex1.test(element)) {
  322. const match = yearRegex1.exec(element);
  323. year = parseInt(match[1]) + 2000; // Convert to full year
  324. month = parseInt(match[2]);
  325. }
  326.  
  327. if (!month && yearRegex2.test(element)) {
  328. const match = yearRegex2.exec(element);
  329. year = parseInt(match[1]);
  330. month = parseInt(match[2]);
  331. }
  332.  
  333. if (!year && yearRegex3.test(element)) {
  334. year = parseInt(element);
  335. }
  336.  
  337. if (!month && monthRegex1.test(element)) {
  338. month = parseInt(element);
  339. }
  340.  
  341. if (!month && monthRegex2.test(element)) {
  342. const months = {
  343. "January": 1, "February": 2, "March": 3, "April": 4,
  344. "May": 5, "June": 6, "July": 7, "August": 8,
  345. "September": 9, "October": 10, "November": 11, "December": 12
  346. };
  347. month = months[element];
  348. }
  349. });
  350. return {year,month}
  351. }
  352.  
  353. function getDirection(heading) {
  354. if (typeof heading !== 'number' || heading < 0 || heading >= 360) {
  355. return 'Unknown direction';
  356. }
  357. const directions = [
  358. { name: 'North', range: [337.5, 22.5] },
  359. { name: 'Northeast', range: [22.5, 67.5] },
  360. { name: 'East', range: [67.5, 112.5] },
  361. { name: 'Southeast', range: [112.5, 157.5] },
  362. { name: 'South', range: [157.5, 202.5] },
  363. { name: 'Southwest', range: [202.5, 247.5] },
  364. { name: 'West', range: [247.5, 292.5] },
  365. { name: 'Northwest', range: [292.5, 337.5] }
  366. ];
  367.  
  368. for (const direction of directions) {
  369. const [start, end] = direction.range;
  370. if (start <= end) {
  371. if (heading >= start && heading < end) {
  372. return direction.name;
  373. }
  374. } else {
  375. if (heading >= start || heading < end) {
  376. return direction.name;
  377. }
  378. }
  379. }
  380.  
  381. return 'Unknown direction';
  382. }
  383.  
  384. function getGeneration(svData,country) {
  385. if (svData&&svData.tiles) {
  386. if (svData.tiles.worldSize.height === 1664) { // Gen 1
  387. return 'Gen1';
  388. } else if (svData.tiles.worldSize.height === 6656) { // Gen 2 or 3
  389.  
  390. let lat;
  391. for (let key in svData.Sv) {
  392. lat = svData.Sv[key].lat;
  393. break;
  394. }
  395.  
  396. let date;
  397. if (svData.imageDate) {
  398. date = new Date(svData.imageDate);
  399. } else {
  400. date = 'nodata';
  401. }
  402.  
  403. if (date!=='nodata'&&((country === 'BD' && (date >= new Date('2021-04'))) ||
  404. (country === 'EC' && (date >= new Date('2022-03'))) ||
  405. (country === 'FI' && (date >= new Date('2020-09'))) ||
  406. (country === 'IN' && (date >= new Date('2021-10'))) ||
  407. (country === 'LK' && (date >= new Date('2021-02'))) ||
  408. (country === 'KH' && (date >= new Date('2022-10'))) ||
  409. (country === 'LB' && (date >= new Date('2021-05'))) ||
  410. (country === 'NG' && (date >= new Date('2021-06'))) ||
  411. (country === 'ST') ||
  412. (country === 'US' && lat > 52 && (date >= new Date('2019-01'))))) {
  413. return 'Shitcam';
  414. }
  415.  
  416. let gen2Countries = ['AU', 'BR', 'CA', 'CL', 'JP', 'GB', 'IE', 'NZ', 'MX', 'RU', 'US', 'IT', 'DK', 'GR', 'RO',
  417. 'PL', 'CZ', 'CH', 'SE', 'FI', 'BE', 'LU', 'NL', 'ZA', 'SG', 'TW', 'HK', 'MO', 'MC', 'SM',
  418. 'AD', 'IM', 'JE', 'FR', 'DE', 'ES', 'PT'];
  419. if (gen2Countries.includes(country)) {
  420.  
  421. return 'Gen2or3';
  422. }
  423. else{
  424. return 'Gen3';}
  425. }
  426. else if(svData.tiles.worldSize.height === 8192){
  427. return 'Gen4';
  428. }
  429. }
  430. return 'Unknown';
  431. }
  432.  
  433. async function getLocal(coord, timestamp) {
  434. const systemTimezoneOffset = -new Date().getTimezoneOffset() * 60;
  435.  
  436. try {
  437. var offset_hours
  438. const timezone=await GeoTZ.find(coord[0],coord[1])
  439.  
  440. const offset = await GeoTZ.toOffset(timezone);
  441.  
  442.  
  443. if(offset){
  444. offset_hours=parseInt(offset/60)
  445. }
  446. const offsetDiff = systemTimezoneOffset -offset_hours*3600;
  447. const convertedTimestamp = Math.round(timestamp - offsetDiff);
  448. return convertedTimestamp;
  449. } catch (error) {
  450. throw error;
  451. }
  452. }
  453.  
  454. async function getWeather(coordinate, timestamp) {
  455. var hours,weatherCodes
  456. const date = new Date(timestamp * 1000);
  457. const formatted_date = date.toISOString().split('T')[0]
  458. try {
  459. if (weatherCache&&!weatherCache[formatted_date]){
  460. const url = `https://archive-api.open-meteo.com/v1/archive?latitude=${coordinate.lat}&longitude=${coordinate.lng}&start_date=${formatted_date}&end_date=${formatted_date}&hourly=weather_code`;
  461. const response = await fetch(url);
  462. const data = await response.json();
  463. hours = data.hourly.time;
  464. weatherCodes = data.hourly.weather_code;
  465. weatherCache[formatted_date]={hours:hours,weatherCodes:weatherCodes}
  466. }
  467. else{
  468. hours = weatherCache[formatted_date].hours
  469. weatherCodes = weatherCache[formatted_date].weatherCodes;
  470. }
  471. const targetHour = new Date(timestamp * 1000).getHours();
  472. let closestHourIndex = 0;
  473. let minDiff = Infinity;
  474.  
  475. for (let i = 0; i < hours.length; i++) {
  476. const hour = new Date(hours[i]).getHours();
  477. const diff = Math.abs(hour - targetHour);
  478.  
  479. if (diff < minDiff) {
  480. minDiff = diff;
  481. closestHourIndex = i;
  482. }
  483. }
  484.  
  485. const weatherCode = weatherCodes[closestHourIndex];
  486. const weatherDescription = weatherCodeMap[weatherCode] || 'Unknown weather code';
  487. return weatherDescription;
  488.  
  489. } catch (error) {
  490. console.error('Error fetching weather data:', error);
  491. return 'Network request failed'
  492. }
  493. }
  494.  
  495. async function processCoord(coord, tags, svData,ccData) {
  496. var panoYear,panoMonth
  497. if (tags.includes(('fix')||('update')||('detect'))){
  498. if (coord.panoDate){
  499. panoYear=parseInt(coord.panoDate.toISOString().substring(0,4))
  500. panoMonth=parseInt(coord.panoDate.toISOString().substring(5,7))
  501. }
  502. else if(coord.panoId&&svData){
  503. panoYear=parseInt(svData.imageDate.substring(0,4))
  504. panoMonth=parseInt(svData.imageDate.substring(5,7))
  505. }
  506. else{
  507. panoYear=parseInt(extractDate(coord.tags).year)
  508. panoMonth=parseInt(extractDate(coord.tags).month)
  509. }}
  510. try{
  511. if (svData||ccData){
  512. let meta=getMetaData(svData)
  513. let yearTag=meta[0]
  514. let monthTag=parseInt(meta[1])
  515. let typeTag=meta[2]
  516. let subdivisionTag=meta[3]
  517. let countryTag,elevationTag
  518. let genTag,trekkerTag,floorTag,driDirTag,weatherTag
  519. let dayTag,timeTag,exactTime,timeRange
  520.  
  521. //if(monthTag){monthTag=months[monthTag-1]}
  522. if(monthTag) monthTag=yearTag.slice(-2)+'-'+(monthTag.toString())
  523. if (!monthTag){monthTag='Month not found'}
  524.  
  525. var date=monthToTimestamp(svData.imageDate)
  526.  
  527. if(tags.includes('day')||tags.includes('time')||tags.includes('sun')||tags.includes('weather')){
  528. const initialSearch=await UE('SingleImageSearch',{lat:coord.location.lat,lng:coord.location.lng},date.startDate,date.endDate,30)
  529. if (initialSearch){
  530. if (initialSearch.length!=3)exactTime=null;
  531. else{
  532. if(tags.includes('weather')) accuracy=700
  533. exactTime=await binarySearch({lat:coord.location.lat,lng:coord.location.lng}, date.startDate,date.endDate,30)
  534. if(tags.includes('weather')) weatherTag=await getWeather(coord.location,exactTime)
  535. if(weatherTag) coord.tags.push(weatherTag)
  536. }
  537. }
  538.  
  539. }
  540.  
  541. if(!exactTime){dayTag='Day not found'
  542. timeTag='Time not found'}
  543. else{
  544.  
  545. if (tags.includes('day')){
  546. const currentDate = new Date();
  547. const currentOffset =-(currentDate.getTimezoneOffset())*60
  548. const dayOffset = currentOffset-Math.round((coord.location.lng / 15) * 3600);
  549. const LocalDay=new Date(Math.round(exactTime-dayOffset)*1000)
  550. dayTag = LocalDay.toISOString().split('T')[0];
  551. }
  552.  
  553. if(tags.includes('time')) {
  554.  
  555. var localTime=await getLocal([coord.location.lat,coord.location.lng],exactTime)
  556. var timeObject=new Date(localTime*1000)
  557. timeTag =`${timeObject.getHours().toString().padStart(2, '0')}:${timeObject.getMinutes().toString().padStart(2, '0')}:${timeObject.getSeconds().toString().padStart(2, '0')}`;
  558. var hour = timeObject.getHours();
  559.  
  560. if (hour < 11) {
  561. timeRange = 'Morning';
  562. } else if (hour >= 11 && hour < 13) {
  563. timeRange = 'Noon';
  564. } else if (hour >= 13 && hour < 17) {
  565. timeRange = 'Afternoon';
  566. } else if(hour >= 17 && hour < 19) {
  567. timeRange = 'Dusk';
  568. }
  569. else{
  570. timeRange = 'Night';
  571. }
  572. }
  573.  
  574. if (tags.includes('sun')){
  575. const utcDate=new Date(exactTime*1000)
  576. const sunData=calSun(utcDate.toISOString(),coord.location.lat,coord.location.lng)
  577. if(sunData){
  578.  
  579. if (exactTime>=(sunData.sunset-30*60)&&exactTime<=(sunData.sunset+30*60)){
  580. coord.tags.push('Sunset')
  581. }
  582. else if (exactTime>=(sunData.sunset-90*60)&&exactTime<=(sunData.sunset+90*60)){
  583. coord.tags.push('Sunset(check)')
  584. }
  585. else if (exactTime>=(sunData.sunrise-30*60)&&exactTime<=(sunData.sunrise+30*60)){
  586. coord.tags.push('Sunrise')
  587. }
  588. else if (exactTime>=(sunData.sunrise-90*60)&&exactTime<=(sunData.sunrise+90*60)){
  589. coord.tags.push('Sunrise(check)')
  590. }
  591. else if (exactTime>=(sunData.noon-30*60)&&exactTime<=(sunData.noon+30*60)){
  592. coord.tags.push('Noon')
  593. }
  594. }
  595. }
  596. }
  597.  
  598. try {if (ccData.length!=3) ccData=ccData[1][0]
  599. else ccData=ccData[1]
  600. }
  601.  
  602. catch (error) {
  603. ccData=null
  604. }
  605.  
  606. if (ccData){
  607. try{
  608. countryTag = ccData[5][0][1][4]}
  609. catch(error){
  610. countryTag=null
  611. }
  612. try{
  613. elevationTag=ccData[5][0][1][1][0]}
  614. catch(error){
  615. elevationTag=null
  616. }
  617. try{
  618. driDirTag=ccData[5][0][1][2][0]}
  619. catch(error){
  620. driDirTag=null
  621. }
  622. try{
  623. trekkerTag=ccData[6][5]}
  624. catch(error){
  625. trekkerTag=null
  626. }
  627. try{
  628. floorTag=ccData[5][0][1][3][2][0]
  629. }
  630. catch(error){
  631. floorTag=null
  632. }
  633. if (tags.includes('detect')){
  634. const defaultDate=3
  635. }
  636. }
  637.  
  638. if (trekkerTag){
  639. trekkerTag=trekkerTag.toString()
  640. if( trekkerTag.includes('scout')){
  641. trekkerTag='trekker'
  642. }
  643. else{
  644. trekkerTag=null
  645. }}
  646.  
  647. if(elevationTag){
  648. elevationTag=Math.round(elevationTag*100)/100
  649. if(sR){
  650. elevationTag=findRange(elevationTag,sR)
  651. }
  652. else{
  653. elevationTag=elevationTag.toString()+'m'
  654. }
  655. }
  656. if(driDirTag){
  657. driDirTag=getDirection(parseFloat(driDirTag))
  658. }
  659. else{
  660. driDirTag='Driving direction not found'
  661. }
  662. if (!countryTag)countryTag='Country not found'
  663. if (!elevationTag)elevationTag='Elevation not found'
  664.  
  665. if (tags.includes('generation')&&typeTag=='Official'&&countryTag){
  666. genTag = getGeneration(svData,countryTag)
  667. coord.tags.push(genTag)}
  668.  
  669. if (tags.includes('year'))coord.tags.push(yearTag)
  670.  
  671. if (tags.includes('month'))coord.tags.push(monthTag)
  672.  
  673. if (tags.includes('day'))coord.tags.push(dayTag)
  674.  
  675. if (tags.includes('time'))coord.tags.push(timeTag)
  676.  
  677. if (tags.includes('time')&&timeRange)coord.tags.push(timeRange)
  678.  
  679. if (tags.includes('type'))coord.tags.push(typeTag)
  680.  
  681. if (tags.includes('driving direction'))coord.tags.push(driDirTag)
  682.  
  683. if (tags.includes('type')&&trekkerTag&&typeTag=='Official')coord.tags.push('trekker')
  684.  
  685. if (tags.includes('type')&&floorTag&&typeTag=='Official')coord.tags.push(floorTag)
  686.  
  687. if (tags.includes('country'))coord.tags.push(countryTag)
  688.  
  689. if (tags.includes('subdivision')&&typeTag=='Official')coord.tags.push(subdivisionTag)
  690.  
  691. if (tags.includes('elevation'))coord.tags.push(elevationTag)
  692.  
  693. if (tags.includes('reset heading')){
  694. if(meta[4]) coord.heading=meta[4]
  695. }
  696.  
  697. if (tags.includes('update')){
  698. try{
  699. const resultPano=await UE('SingleImageSearch',{lat: coord.location.lat, lng: coord.location.lng},null,null,50)
  700. const updatedPnaoId=resultPano[1][1][1]
  701. const updatedYear=resultPano[1][6][7][0]
  702. const updatedMonth=resultPano[1][6][7][1]
  703. coord.panoId=updatedPnaoId
  704.  
  705. if (coord.panoId){
  706. if (updatedPnaoId&&updatedPnaoId!=coord.panoId) {
  707. if(panoYear!=updatedYear||panoMonth!=updatedMonth){
  708. const orginLoc=coord
  709. coord.panoId=updatedPnaoId
  710. coord.tags.push('Updated')}
  711. else{
  712. const orginLoc=coord
  713. coord.panoId=updatedPnaoId
  714. coord.tags.push('Copyright changed')
  715. }
  716. }
  717. }
  718. else{
  719. if (panoYear&&panoMonth&&updatedYear&&updatedMonth){
  720. if(panoYear!=updatedYear||panoMonth!=updatedMonth){
  721. const orginLoc=coord
  722. coord.panoId=updatedPnaoId
  723. coord.tags.push('Updated')
  724. }
  725. }
  726. else{
  727. coord.tags.push('Failed to update')
  728. }
  729. }
  730. }
  731. catch (error){
  732. coord.tags.push('Failed to update')
  733. }
  734. }
  735. }
  736. }
  737. catch (error) {
  738. if(!tags.includes('fix')&&!tags.includes('update'))coord.tags.push('Pano not found');
  739.  
  740. else if (tags.includes('update')){
  741. try{
  742. const resultPano=await UE('SingleImageSearch',{lat: coord.location.lat, lng: coord.location.lng},null,null,50)
  743. const updatedPnaoId=resultPano[1][1][1]
  744. const updatedYear=resultPano[1][6][7][0]
  745. const updatedMonth=resultPano[1][6][7][1]
  746. coord.panoId=updatedPnaoId
  747. coord.location.lat=resultPano[1][5][0][1][0][2]
  748. coord.location.lng=resultPano[1][5][0][1][0][3]
  749. }
  750. catch (error){
  751. coord.tags.push('Failed to update')
  752. }
  753. }
  754. else{
  755. var fixState
  756. try{
  757. const resultPano=await UE('SingleImageSearch',{lat: coord.location.lat, lng: coord.location.lng},null,null,30)
  758. if(fixStrategy){
  759. const panos=resultPano[1][5][0][8]
  760. for(const pano of panos){
  761. if(pano[1][0]===panoYear&&pano[1][1]===panoMonth){
  762. const panoIndex=pano[0]
  763. const fixedPanoId=resultPano[1][5][0][3][0][panoIndex][0][1]
  764. coord.panoId=fixedPanoId
  765. coord.location.lat=resultPano[1][5][0][1][0][2]
  766. coord.location.lng=resultPano[1][5][0][1][0][3]
  767. fixState=true
  768. }
  769. }
  770. }
  771. else{
  772. coord.panoId=resultPano[1][1][1]
  773. coord.location.lat=resultPano[1][5][0][1][0][2]
  774. coord.location.lng=resultPano[1][5][0][1][0][3]
  775. fixState=true
  776. }
  777.  
  778. }
  779. catch (error){
  780. fixState=null
  781. }
  782. if (!fixState)coord.tags.push('Failed to fix')
  783. else coord.tags.push('Fixed')
  784.  
  785. }
  786. }
  787. if (coord.tags) { coord.tags = Array.from(new Set(coord.tags))}
  788. taggedLocs.push(coord);
  789. }
  790.  
  791. async function processChunk(chunk, tags) {
  792. var service = new google.maps.StreetViewService();
  793. var promises = chunk.map(async coord => {
  794. let panoId = coord.panoId;
  795. let latLng = {lat: coord.location.lat, lng: coord.location.lng};
  796. let svData;
  797. let ccData;
  798. if ((panoId || latLng)) {
  799. if(tags!=['country']&&tags!=['elevation']&&tags!=['detect']){
  800. svData = await getSVData(service, panoId ? {pano: panoId} : {location: latLng, radius: 50});}
  801. }
  802.  
  803. if (tags.includes('generation')||('country')||('elevation')||('type')||('driving direction')) {
  804. if(!panoId)ccData = await UE('SingleImageSearch', latLng);
  805. else ccData = await UE('GetMetadata', panoId);
  806. }
  807.  
  808. if (latLng && (tags.includes('detect'))) {
  809. var detectYear,detectMonth
  810. if (coord.panoDate){
  811. detectYear=parseInt(coord.panoDate.toISOString().substring(0,4))
  812. detectMonth=parseInt(coord.panoDate.toISOString().substring(5,7))
  813. }
  814. else{
  815. if(coord.panoId){
  816. const metaData=await getSVData(service,{pano: panoId})
  817. if (metaData){
  818. if(metaData.imageDate){
  819. detectYear=parseInt(metaData.imageDate.substring(0,4))
  820. detectMonth=parseInt(metaData.imageDate.substring(5,7))
  821. }
  822. }
  823. }
  824. }
  825. if (detectYear&&detectMonth){
  826. const metaData = await UE('SingleImageSearch', latLng,10);
  827. if (metaData){
  828. if(metaData.length>1){
  829. const defaultDate=metaData[1][6][7]
  830. if (defaultDate[0]===detectYear&&defaultDate[1]!=detectMonth){
  831. coord.tags.push('Dangerous')}
  832. }
  833. }
  834. }
  835. }
  836. if (tags!=['detect']){
  837. await processCoord(coord, tags, svData,ccData)}
  838. });
  839. await Promise.all(promises);
  840. }
  841.  
  842. function getSVData(service, options) {
  843. return new Promise(resolve => service.getPanorama({...options}, (data, status) => {
  844. resolve(data);
  845.  
  846. }));
  847. }
  848.  
  849. async function processData(tags) {
  850. let successText = 'The JSON data has been pasted to your clipboard!';
  851. try {
  852. const totalChunks = Math.ceil(selections.length / CHUNK_SIZE);
  853. let processedChunks = 0;
  854.  
  855. const swal = Swal.fire({
  856. title: 'Tagging',
  857. text: 'If you try to tag a large number of locs by exact time, it could take quite some time. Please wait...',
  858. allowOutsideClick: false,
  859. allowEscapeKey: false,
  860. showConfirmButton: false,
  861. icon:"info",
  862. didOpen: () => {
  863. Swal.showLoading();
  864. }
  865. });
  866.  
  867. for (let i = 0; i < selections.length; i += CHUNK_SIZE) {
  868. let chunk = selections.slice(i, i + CHUNK_SIZE);
  869. await processChunk(chunk, tags);
  870. processedChunks++;
  871.  
  872. const progress = Math.min((processedChunks / totalChunks) * 100, 100);
  873. Swal.update({
  874. html: `<div>${progress.toFixed(2)}% completed</div>
  875. <div class="swal2-progress">
  876. <div class="swal2-progress-bar" role="progressbar" aria-valuenow="${progress}" aria-valuemin="0" aria-valuemax="100" style="width: ${progress}%;">
  877. </div>
  878. </div>`
  879. });
  880. }
  881.  
  882.  
  883. swal.close();
  884. var newJSON=[]
  885. if (exportMode) {
  886. updateLocation(selections,taggedLocs)
  887. successText = 'Tagging completed! Please save the map and refresh the page(The JSON data is also pasted to your clipboard)'
  888. }
  889. taggedLocs.forEach((loc)=>{
  890. newJSON.push({lat:loc.location.lat,
  891. lng:loc.location.lng,
  892. heading:loc.heading,
  893. pitch: loc.pitch !== undefined && loc.pitch !== null ? loc.pitch : 90,
  894. zoom: loc.zoom !== undefined && loc.zoom !== null ? loc.zoom : 0,
  895. panoId:loc.panoId,
  896. extra:{tags:loc.tags}
  897. })
  898. })
  899. GM_setClipboard(JSON.stringify(newJSON))
  900. Swal.fire({
  901. title: 'Success!',
  902. text: successText,
  903. icon: 'success',
  904. showCancelButton: true,
  905. confirmButtonColor: '#3085d6',
  906. cancelButtonColor: '#d33',
  907. confirmButtonText: 'OK'
  908. })
  909. } catch (error) {
  910. swal.close();
  911. Swal.fire('Error Tagging!', '','error');
  912. console.error('Error processing JSON data:', error);
  913. }
  914. }
  915.  
  916. }
  917.  
  918. function chunkArray(array, maxSize) {
  919. const result = [];
  920. for (let i = 0; i < array.length; i += maxSize) {
  921. result.push(array.slice(i, i + maxSize));
  922. }
  923. return result;
  924. }
  925.  
  926. function generateCheckboxHTML(tags) {
  927.  
  928. const half = Math.ceil(tags.length / 2);
  929. const firstHalf = tags.slice(0, half);
  930. const secondHalf = tags.slice(half);
  931.  
  932. return `
  933. <div style="display: flex; flex-wrap: wrap; gap: 10px; text-align: left;">
  934. <div style="flex: 1; min-width: 150px;">
  935. ${firstHalf.map((tag, index) => `
  936. <label style="display: block; margin-bottom: 12px; margin-left: 40px; font-size: 15px;" title="${tooltips[tag]}">
  937. <input type="checkbox" class="feature-checkbox" value="${tag}" /> <span style="font-size: 14px;">${tag}</span>
  938. </label>
  939. `).join('')}
  940. </div>
  941. <div style="flex: 1; min-width: 150px;">
  942. ${secondHalf.map((tag, index) => `
  943. <label style="display: block; margin-bottom: 12px; margin-left: 40px; font-size: 15px;" title="${tooltips[tag]}">
  944. <input type="checkbox" class="feature-checkbox" value="${tag}" /> <span style="font-size: 14px;">${tag}</span>
  945. </label>
  946. `).join('')}
  947. </div>
  948. <div style="flex: 1; min-width: 150px; margin-top: 12px; text-align: center;">
  949. <label style="display: block; font-size: 14px;">
  950. <input type="checkbox" class="feature-checkbox" id="selectAll" /> <span style="font-size: 16px;">Select All</span>
  951. </label>
  952. </div>
  953. </div>
  954. `;
  955. }
  956.  
  957. function showFeatureSelectionPopup() {
  958. const checkboxesHTML = generateCheckboxHTML(tagBox);
  959.  
  960. Swal.fire({
  961. title: 'Select Features',
  962. html: `
  963. ${checkboxesHTML}
  964. `,
  965. icon: 'question',
  966. showCancelButton: true,
  967. showCloseButton: true,
  968. allowOutsideClick: false,
  969. confirmButtonColor: '#3085d6',
  970. cancelButtonColor: '#d33',
  971. confirmButtonText: 'Start Tagging',
  972. cancelButtonText: 'Cancel',
  973. didOpen: () => {
  974. const selectAllCheckbox = Swal.getPopup().querySelector('#selectAll');
  975. const featureCheckboxes = Swal.getPopup().querySelectorAll('.feature-checkbox:not(#selectAll)');
  976.  
  977. selectAllCheckbox.addEventListener('change', () => {
  978. featureCheckboxes.forEach(checkbox => {
  979. checkbox.checked = selectAllCheckbox.checked;
  980. });
  981. });
  982.  
  983.  
  984. featureCheckboxes.forEach(checkbox => {
  985. checkbox.addEventListener('change', () => {
  986.  
  987. const allChecked = Array.from(featureCheckboxes).every(checkbox => checkbox.checked);
  988. selectAllCheckbox.checked = allChecked;
  989. });
  990. });
  991. },
  992. preConfirm: () => {
  993. const selectedFeatures = [];
  994. const featureCheckboxes = Swal.getPopup().querySelectorAll('.feature-checkbox:not(#selectAll)');
  995.  
  996. featureCheckboxes.forEach(checkbox => {
  997. if (checkbox.checked) {
  998. selectedFeatures.push(checkbox.value.toLowerCase());
  999. }
  1000. });
  1001.  
  1002. return selectedFeatures;
  1003. }
  1004. }).then((result) => {
  1005. if (result.isConfirmed) {
  1006. const selectedFeatures = result.value;
  1007. handleSelectedFeatures(selectedFeatures);
  1008. } else if (result.dismiss === Swal.DismissReason.cancel) {
  1009. console.log('User canceled');
  1010. }
  1011. });
  1012. }
  1013.  
  1014. function handleSelectedFeatures(features) {
  1015. if (features.includes('elevation')) {
  1016. Swal.fire({
  1017. title: 'Set A Range For Elevation',
  1018. text: 'If you select "Cancel", the script will return the exact elevation for each location.',
  1019. icon: 'question',
  1020. showCancelButton: true,
  1021. showCloseButton: true,
  1022. allowOutsideClick: false,
  1023. confirmButtonColor: '#3085d6',
  1024. cancelButtonColor: '#d33',
  1025. confirmButtonText: 'Yes',
  1026. cancelButtonText: 'Cancel'
  1027. }).then((result) => {
  1028. if (result.isConfirmed) {
  1029. Swal.fire({
  1030. title: 'Define Range for Each Segment',
  1031. html: `
  1032. <label> <br>Enter range for each segment, separated by commas</br></label>
  1033. <textarea id="segmentRanges" class="swal2-textarea" placeholder="such as:-1-10,11-35"></textarea>
  1034. `,
  1035. icon: 'question',
  1036. showCancelButton: true,
  1037. showCloseButton: true,
  1038. allowOutsideClick: false,
  1039. focusConfirm: false,
  1040. preConfirm: () => {
  1041. const segmentRangesInput = document.getElementById('segmentRanges').value.trim();
  1042. if (!segmentRangesInput) {
  1043. Swal.showValidationMessage('Please enter range for each segment');
  1044. return false;
  1045. }
  1046. const segmentRanges = segmentRangesInput.split(',');
  1047. const validatedRanges = segmentRanges.map(range => {
  1048. const matches = range.trim().match(/^\s*(-?\d+)\s*-\s*(-?\d+)\s*$/);
  1049. if (matches) {
  1050. const min = Number(matches[1]);
  1051. const max = Number(matches[2]);
  1052. return { min, max };
  1053. } else {
  1054. Swal.showValidationMessage('Invalid range format. Please use format: minValue-maxValue');
  1055. return false;
  1056. }
  1057. });
  1058. return validatedRanges.filter(Boolean);
  1059. },
  1060. confirmButtonColor: '#3085d6',
  1061. cancelButtonColor: '#d33',
  1062. confirmButtonText: 'Yes',
  1063. cancelButtonText: 'Cancel',
  1064. inputValidator: (value) => {
  1065. if (!value.trim()) {
  1066. return 'Please enter range for each segment';
  1067. }
  1068. }
  1069. }).then((result) => {
  1070. if (result.isConfirmed) {
  1071. runScript(features, result.value);
  1072. } else {
  1073. Swal.showValidationMessage('You canceled input');
  1074. }
  1075. });
  1076. } else if (result.dismiss === Swal.DismissReason.cancel) {
  1077. runScript(features);
  1078. }
  1079. });
  1080. } else {
  1081. runScript(features);
  1082. }
  1083. }
  1084.  
  1085. function calSun(date,lat,lng){
  1086. if (lat && lng && date) {
  1087. const format_date = new Date(date);
  1088. const times = SunCalc.getTimes(format_date, lat, lng);
  1089. const sunsetTimestamp = Math.round(times.sunset.getTime() / 1000);
  1090. const sunriseTimestamp = Math.round(times.sunrise.getTime() / 1000);
  1091. const noonTimestamp = Math.round(times.solarNoon.getTime() / 1000);
  1092.  
  1093. return {
  1094. sunset: sunsetTimestamp,
  1095. sunrise: sunriseTimestamp,
  1096. noon: noonTimestamp,
  1097. };
  1098. }
  1099. }
  1100.  
  1101. var mainButton = document.createElement('button');
  1102. mainButton.textContent = 'Auto-Tag';
  1103. mainButton.id = 'main-button';
  1104. mainButton.style.position = 'fixed';
  1105. mainButton.style.right = '20px';
  1106. mainButton.style.bottom = '15px';
  1107. mainButton.style.borderRadius = '18px';
  1108. mainButton.style.fontSize = '15px';
  1109. mainButton.style.padding = '10px 20px';
  1110. mainButton.style.border = 'none';
  1111. mainButton.style.color = 'white';
  1112. mainButton.style.cursor = 'pointer';
  1113. mainButton.style.backgroundColor = '#4CAF50';
  1114. mainButton.addEventListener('click', showFeatureSelectionPopup);
  1115. document.body.appendChild(mainButton)
  1116.  
  1117. })();