Geoguessr Map-Making Auto-Tag

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

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