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.7
  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 === 8192){
  393. return 'Gen4';
  394. }
  395. else if (svData.tiles.worldSize.height === 6656) { // Gen 2 or 3
  396. const lat = Object.values(svData.Sv)[0]?.lat;
  397. let date;
  398. if (svData.imageDate) {
  399. date = new Date(svData.imageDate);
  400. }
  401. if (date&&((country === 'BD' && (date >= new Date('2021-04'))) ||
  402. (country === 'EC' && (date >= new Date('2022-03'))) ||
  403. (country === 'FI' && (date >= new Date('2020-09'))) ||
  404. (country === 'IN' && (date >= new Date('2021-10'))) ||
  405. (country === 'LK' && (date >= new Date('2021-02'))) ||
  406. (country === 'KH' && (date >= new Date('2022-10'))) ||
  407. (country === 'LB' && (date >= new Date('2021-05'))) ||
  408. (country === 'NG' && (date >= new Date('2021-06'))) ||
  409. (country === 'ST') ||
  410. (country === 'US' && lat > 52 && (date >= new Date('2019-01'))))) {
  411. return 'Badcam';
  412. }
  413. if (gen2Countries.includes(country)&&date <= new Date('2011-11')) {
  414. return date >= new Date('2010-09') ?'Gen2/3':'Gen2';
  415. }
  416. return 'Gen3'
  417. }
  418. else if (svData.tiles.worldSize.height === 1664) { // Gen 1
  419. return 'Gen1';
  420. }
  421. }
  422. return 'Ari';
  423. }
  424.  
  425. async function getLocal(coord, timestamp) {
  426. const systemTimezoneOffset = -new Date().getTimezoneOffset() * 60;
  427.  
  428. try {
  429. var offset_hours
  430. const timezone=await GeoTZ.find(coord[0],coord[1])
  431.  
  432. const offset = await GeoTZ.toOffset(timezone);
  433.  
  434. if(offset){
  435. offset_hours=parseInt(offset/60)
  436. }
  437. else if (offset===0) offset_hours=0
  438. const offsetDiff = systemTimezoneOffset -offset_hours*3600;
  439. const convertedTimestamp = Math.round(timestamp - offsetDiff);
  440. return convertedTimestamp;
  441. } catch (error) {
  442. throw error;
  443. }
  444. }
  445.  
  446. async function getWeather(coordinate, timestamp) {
  447. var hours,weatherCodes
  448. const date = new Date(timestamp * 1000);
  449. const formatted_date = date.toISOString().split('T')[0]
  450. try {
  451. 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`;
  452. const response = await fetch(url);
  453. const data = await response.json();
  454. hours = data.hourly.time;
  455. weatherCodes = data.hourly.weather_code;
  456.  
  457. const targetHour = new Date(timestamp * 1000).getHours();
  458. let closestHourIndex = 0;
  459. let minDiff = Infinity;
  460.  
  461. for (let i = 0; i < hours.length; i++) {
  462. const hour = new Date(hours[i]).getHours();
  463. const diff = Math.abs(hour - targetHour);
  464.  
  465. if (diff < minDiff) {
  466. minDiff = diff;
  467. closestHourIndex = i;
  468. }
  469. }
  470.  
  471. const weatherCode = weatherCodes[closestHourIndex];
  472. const weatherDescription = weatherCodeMap[weatherCode] || 'Unknown weather code';
  473. return weatherDescription;
  474.  
  475. } catch (error) {
  476. console.error('Error fetching weather data:', error);
  477. return 'Network request failed'
  478. }
  479. }
  480.  
  481. async function processCoord(coord, tags, svData,ccData) {
  482. var panoYear,panoMonth
  483. if (tags.includes(('fix')||('update')||('detect'))){
  484. if (coord.panoDate){
  485. panoYear=parseInt(coord.panoDate.toISOString().substring(0,4))
  486. panoMonth=parseInt(coord.panoDate.toISOString().substring(5,7))
  487. }
  488. else if(svData&&svData.imageDate){
  489. panoYear=parseInt(svData.imageDate.substring(0,4))
  490. panoMonth=parseInt(svData.imageDate.substring(5,7))
  491.  
  492. }
  493. else{
  494. panoYear=parseInt(extractDate(coord.tags).year)
  495. panoMonth=parseInt(extractDate(coord.tags).month)
  496. }
  497. }
  498. try{
  499. let meta=getMetaData(svData)
  500. let yearTag=meta[0]
  501. let monthTag=parseInt(meta[1])
  502. let typeTag=meta[2]
  503. let subdivisionTag=meta[3]
  504. let countryTag,elevationTag
  505. let genTag,trekkerTag,floorTag,driDirTag,weatherTag,roadTag
  506. let dayTag,timeTag,exactTime,timeRange
  507.  
  508. //if(monthTag){monthTag=months[monthTag-1]}
  509. if(yearTag&&monthTag) monthTag=yearTag.slice(-2)+'-'+(monthTag.toString())
  510. if (!monthTag){monthTag='Month not found'}
  511.  
  512. if(svData){
  513. var date=monthToTimestamp(svData.imageDate)
  514.  
  515. if(tags.includes('day')||tags.includes('time')||tags.includes('sun')||tags.includes('weather')||tags.includes('pan to sun')){
  516. const initialSearch=await UE('SingleImageSearch',{lat:coord.location.lat,lng:coord.location.lng},date.startDate,date.endDate,15)
  517. if (initialSearch){
  518. if (initialSearch.length!=3)exactTime=null;
  519. else{
  520. if(!tags.includes('day')) accuracy=18000
  521. if(tags.includes('weather')) accuracy=600
  522. if (tags.includes('sun')) accuracy=300
  523. if (tags.includes('pan to sun')) accuracy=300
  524. if (tags.includes('time')) accuracy=60
  525. exactTime=await binarySearch({lat:coord.location.lat,lng:coord.location.lng}, date.startDate,date.endDate)
  526. }
  527. }
  528. }
  529. }
  530.  
  531. if(!exactTime){dayTag='Day not found'
  532. timeTag='Time not found'}
  533. else{
  534.  
  535. if (tags.includes('day')){
  536. const currentDate = new Date();
  537. const currentOffset =-(currentDate.getTimezoneOffset())*60
  538. const dayOffset = currentOffset-Math.round((coord.location.lng / 15) * 3600);
  539. const LocalDay=new Date(Math.round(exactTime-dayOffset)*1000)
  540. dayTag = LocalDay.toISOString().split('T')[0];
  541. }
  542.  
  543. if(tags.includes('time')) {
  544.  
  545. var localTime=await getLocal([coord.location.lat,coord.location.lng],exactTime)
  546. var timeObject=new Date(localTime*1000)
  547. timeTag =`${timeObject.getHours().toString().padStart(2, '0')}:${timeObject.getMinutes().toString().padStart(2, '0')}:${timeObject.getSeconds().toString().padStart(2, '0')}`;
  548. var hour = timeObject.getHours();
  549.  
  550. if (hour < 11) {
  551. timeRange = 'Morning';
  552. } else if (hour >= 11 && hour < 13) {
  553. timeRange = 'Noon';
  554. } else if (hour >= 13 && hour < 17) {
  555. timeRange = 'Afternoon';
  556. } else if(hour >= 17 && hour < 19) {
  557. timeRange = 'Dusk';
  558. }
  559. else{
  560. timeRange = 'Night';
  561. }
  562. }
  563.  
  564. if (tags.includes('sun')){
  565. const utcDate=new Date(exactTime*1000)
  566. const sunData=calSun(utcDate.toISOString(),coord.location.lat,coord.location.lng)
  567. if(sunData){
  568. if (exactTime>=(sunData.sunset-30*60)&&exactTime<=(sunData.sunset+30*60)){
  569. coord.tags.push('Sunset')
  570. }
  571. else if (exactTime>=(sunData.sunset-90*60)&&exactTime<=(sunData.sunset+90*60)){
  572. coord.tags.push('Sunset(check)')
  573. }
  574. else if (exactTime>=(sunData.sunrise-30*60)&&exactTime<=(sunData.sunrise+30*60)){
  575. coord.tags.push('Sunrise')
  576. }
  577. else if (exactTime>=(sunData.sunrise-90*60)&&exactTime<=(sunData.sunrise+90*60)){
  578. coord.tags.push('Sunrise(check)')
  579. }
  580. else if (exactTime>=(sunData.noon-30*60)&&exactTime<=(sunData.noon+30*60)){
  581. coord.tags.push('Noon')
  582. }
  583. }
  584. }
  585.  
  586. if (tags.includes('pan to sun')){
  587. const date = new Date(exactTime * 1000);
  588. const position = SunCalc.getPosition(date, coord.location.lat, coord.location.lng);
  589.  
  590. const altitude = position.altitude;
  591. const azimuth = position.azimuth;
  592.  
  593. const altitudeDegrees = altitude * (180 / Math.PI);
  594. const azimuthDegrees = azimuth * (180 / Math.PI);
  595. if(azimuthDegrees&&altitudeDegrees){
  596. if (altitudeDegrees<0){
  597. const moonPosition = SunCalc.getMoonPosition(date, coord.location.lat, coord.location.lng);
  598. const moon_altitude = moonPosition.altitude;
  599. const moon_azimuth = moonPosition.azimuth;
  600. const moon_altitudeDegrees = moon_altitude * (180 / Math.PI);
  601. const moon_azimuthDegrees = moon_azimuth * (180 / Math.PI);
  602. coord.heading=moon_azimuthDegrees+180
  603. coord.pitch=moon_altitudeDegrees
  604. coord.zoom=2
  605. coord.tags.push('pan to moon')
  606. }
  607. else{
  608. coord.heading=azimuthDegrees+180
  609. coord.pitch=altitudeDegrees
  610. coord.tags.push('pan to sun')
  611. }
  612. }
  613. }
  614.  
  615. if(tags.includes('weather')) {
  616. weatherTag=await getWeather(coord.location,exactTime)
  617. if(weatherTag) coord.tags.push(weatherTag)
  618. }
  619. }
  620.  
  621. try {if (ccData.length!=3) ccData=ccData[1][0]
  622. else ccData=ccData[1]
  623. }
  624. catch (error) {
  625. ccData=null
  626. }
  627.  
  628. if (ccData){
  629. try{
  630. countryTag = ccData[5][0][1][4]}
  631. catch(error){
  632. countryTag=null
  633. }
  634. try{
  635. elevationTag=ccData[5][0][1][1][0]}
  636. catch(error){
  637. elevationTag=null
  638. }
  639. try{
  640. roadTag=ccData[5][0][12][0][0][0][2][0]}
  641. catch(error){
  642. roadTag=null
  643. }
  644. try{
  645. driDirTag=ccData[5][0][1][2][0]}
  646. catch(error){
  647. driDirTag=null
  648. }
  649. try{
  650. trekkerTag=ccData[6][5]}
  651. catch(error){
  652. trekkerTag=null
  653. }
  654. try{
  655. floorTag=ccData[5][0][1][3][2][0]
  656. }
  657. catch(error){
  658. floorTag=null
  659. }
  660. if (tags.includes('detect')){
  661. const defaultDate=3
  662. }
  663. }
  664. if (roadTag==''||!roadTag)roadTag='Road not found'
  665. if (trekkerTag){
  666. trekkerTag=trekkerTag.toString()
  667. if( trekkerTag.includes('scout')&&floorTag){
  668. trekkerTag='trekker'
  669. }
  670. else{
  671. trekkerTag=false
  672. }}
  673.  
  674. if(driDirTag){
  675. driDirTag=getDirection(parseFloat(driDirTag))
  676. }
  677. else{
  678. driDirTag='Driving direction not found'
  679. }
  680. if (!countryTag)countryTag='Country not found'
  681. if (!elevationTag)elevationTag='Elevation not found'
  682.  
  683. if (tags.includes('generation')&&typeTag=='Official'&&countryTag){
  684. genTag = getGeneration(svData,countryTag)
  685. coord.tags.push(genTag)
  686. if(elevationTag &&genTag=='Gen4') {
  687. const previous=svData.time[svData.time.length-2].pano
  688. const previous_svData=await UE('GetMetadata',previous)
  689. if(previous_svData){
  690. const previous_elevation=previous_svData[1][0][5][0][1][1][0]
  691. const is_gen4=previous_svData[1][0][2][2][0]==8192
  692. if (Math.abs(previous_elevation-elevationTag)<=0.6 &&Math.abs(previous_elevation-elevationTag>=0.35)&&is_gen4){
  693. coord.tags.push('smallcam')
  694. }
  695. }
  696. }
  697. }
  698. if(elevationTag){
  699. elevationTag=Math.round(elevationTag*100)/100
  700. if(sR){
  701. elevationTag=findRange(elevationTag,sR)
  702. }
  703. else{
  704. elevationTag=elevationTag.toString()+'m'
  705. }
  706. }
  707. if (tags.includes('year'))coord.tags.push(yearTag)
  708.  
  709. if (tags.includes('month'))coord.tags.push(monthTag)
  710.  
  711. if (tags.includes('day'))coord.tags.push(dayTag)
  712.  
  713. if (tags.includes('time'))coord.tags.push(timeTag)
  714.  
  715. if (tags.includes('time')&&timeRange)coord.tags.push(timeRange)
  716.  
  717. if (tags.includes('type'))coord.tags.push(typeTag)
  718.  
  719. if (tags.includes('driving direction'))coord.tags.push(driDirTag)
  720.  
  721. if (tags.includes('road')&&typeTag=='Official')coord.tags.push(roadTag)
  722.  
  723. if (tags.includes('type')&&trekkerTag&&typeTag=='Official')coord.tags.push('trekker')
  724.  
  725. if (tags.includes('type')&&floorTag&&typeTag=='Official')coord.tags.push(floorTag)
  726.  
  727. if (tags.includes('country'))coord.tags.push(countryTag)
  728.  
  729. if (tags.includes('subdivision')&&typeTag=='Official')coord.tags.push(subdivisionTag)
  730.  
  731. if (tags.includes('elevation'))coord.tags.push(elevationTag)
  732.  
  733. if (tags.includes('reset heading')){
  734. if(meta[4]) coord.heading=meta[4]
  735. }
  736.  
  737. if (tags.includes('update')){
  738. try{
  739. const resultPano=await UE('SingleImageSearch',{lat: coord.location.lat, lng: coord.location.lng},null,null,50)
  740. const updatedPnaoId=resultPano[1][1][1]
  741. const updatedYear=resultPano[1][6][7][0]
  742. const updatedMonth=resultPano[1][6][7][1]
  743. if (coord.panoId){
  744. if (updatedPnaoId&&updatedPnaoId!=coord.panoId) {
  745. if(panoYear!=updatedYear||panoMonth!=updatedMonth){
  746. coord.panoId=updatedPnaoId
  747. coord.tags.push('Updated')}
  748. else{
  749. coord.panoId=updatedPnaoId
  750. coord.tags.push('Copyright changed')
  751. }
  752. }
  753. }
  754. else{
  755. if (panoYear&&panoMonth&&updatedYear&&updatedMonth){
  756. if(panoYear!=updatedYear||panoMonth!=updatedMonth){
  757. coord.panoId=updatedPnaoId
  758. coord.tags.push('Updated')
  759. }
  760. }
  761. else{
  762. coord.panoId=svData.location.pano
  763. coord.tags.push('PanoId is added')
  764. }
  765. }
  766. }
  767. catch (error){
  768. coord.tags.push('Failed to update')
  769. }
  770. }
  771.  
  772. else if (tags.includes('fix')){
  773. var fixState
  774. try{
  775. const resultPano=await UE('SingleImageSearch',{lat: coord.location.lat, lng: coord.location.lng},null,null,30)
  776. if(fixStrategy){
  777. const panos=resultPano[1][5][0][8]
  778. if(resultPano[1][6][7][0]===panoYear&&resultPano[1][6][7][1]==panoMonth){
  779. coord.panoId=resultPano[1][1][1]
  780. coord.location.lat=resultPano[1][5][0][1][0][2]
  781. coord.location.lng=resultPano[1][5][0][1][0][3]
  782. fixState=true
  783. }
  784. else{
  785. for(const pano of panos){
  786. if(pano[1][0]===panoYear&&pano[1][1]===panoMonth){
  787. const panoIndex=pano[0]
  788. const fixedPanoId=resultPano[1][5][0][3][0][panoIndex][0][1]
  789. coord.panoId=fixedPanoId
  790. coord.location.lat=resultPano[1][5][0][1][0][2]
  791. coord.location.lng=resultPano[1][5][0][1][0][3]
  792. fixState=true
  793. }
  794. }
  795. }
  796. }
  797. else{
  798. coord.panoId=resultPano[1][1][1]
  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. catch (error){
  806.  
  807. fixState=null
  808. }
  809. if (!fixState)coord.tags.push('Failed to fix')
  810. else coord.tags.push('Fixed')
  811.  
  812. }
  813. }
  814. catch (error) {
  815. if(!svData)coord.tags.push('Pano not found');
  816. else coord.tags.push('Failed to tag')
  817. }
  818. if (coord.tags) { coord.tags = Array.from(new Set(coord.tags))}
  819. taggedLocs.push(coord);
  820. }
  821.  
  822. async function processChunk(chunk, tags) {
  823. var service = new google.maps.StreetViewService();
  824. var panoSource= google.maps.StreetViewSource.GOOGLE
  825. var promises = chunk.map(async coord => {
  826. let panoId = coord.panoId;
  827. let latLng = {lat: coord.location.lat, lng: coord.location.lng};
  828. let svData;
  829. let ccData;
  830. if ((panoId || latLng)) {
  831. if(tags!=['country']&&tags!=['elevation']&&tags!=['detect']){
  832. svData = await getSVData(service, panoId ? {pano: panoId} : {location: latLng, radius: 50,source:panoSource});
  833. }
  834. }
  835.  
  836. if (tags.includes('generation')||tags.includes('country')||tags.includes('elevation')||tags.includes('type')||tags.includes('driving direction')||tags.includes('road')) {
  837. if(!panoId)ccData = await UE('SingleImageSearch', latLng);
  838. else ccData = await UE('GetMetadata', panoId);
  839. }
  840.  
  841. if (latLng && (tags.includes('detect'))) {
  842. var detectYear,detectMonth
  843. if (coord.panoDate){
  844. detectYear=parseInt(coord.panoDate.toISOString().substring(0,4))
  845. detectMonth=parseInt(coord.panoDate.toISOString().substring(5,7))
  846. }
  847. else{
  848. if(coord.panoId){
  849. const metaData=await getSVData(service,{pano: panoId})
  850. if (metaData){
  851. if(metaData.imageDate){
  852. detectYear=parseInt(metaData.imageDate.substring(0,4))
  853. detectMonth=parseInt(metaData.imageDate.substring(5,7))
  854. }
  855. }
  856. }
  857. }
  858. if (detectYear&&detectMonth){
  859. const metaData = await UE('SingleImageSearch', latLng,10);
  860. if (metaData){
  861. if(metaData.length>1){
  862. const defaultDate=metaData[1][6][7]
  863. if (defaultDate[0]===detectYear&&defaultDate[1]!=detectMonth){
  864. coord.tags.push('Dangerous')}
  865. }
  866. }
  867. }
  868. }
  869. if (panoId && tags.includes('brightness')){
  870. const brightness=await getBrightness(panoId)
  871. if (brightness<45) coord.tags.push('Dim')
  872. else if (brightness<90)coord.tags.push('Normal')
  873. else if (brightness<160)coord.tags.push('Lightful')
  874. else coord.tags.push('Overexposed')
  875. }
  876. await processCoord(coord, tags, svData,ccData)
  877. });
  878. await Promise.all(promises);
  879. }
  880.  
  881. function getSVData(service, options) {
  882. return new Promise(resolve => service.getPanorama({...options}, (data, status) => {
  883. resolve(data);
  884.  
  885. }));
  886. }
  887.  
  888. async function processData(tags) {
  889. let successText = 'The JSON data has been pasted to your clipboard!';
  890. try {
  891. const totalChunks = Math.ceil(selections.length / CHUNK_SIZE);
  892. let processedChunks = 0;
  893.  
  894. const swal = Swal.fire({
  895. title: 'Tagging',
  896. text: 'If you try to tag a large number of locs by exact time, it could take quite some time. Please wait...',
  897. allowOutsideClick: false,
  898. allowEscapeKey: false,
  899. showConfirmButton: false,
  900. icon:"info",
  901. didOpen: () => {
  902. Swal.showLoading();
  903. }
  904. });
  905.  
  906. for (let i = 0; i < selections.length; i += CHUNK_SIZE) {
  907. let chunk = selections.slice(i, i + CHUNK_SIZE);
  908. await processChunk(chunk, tags);
  909. processedChunks++;
  910.  
  911. const progress = Math.min((processedChunks / totalChunks) * 100, 100);
  912. Swal.update({
  913. html: `<div>${progress.toFixed(2)}% completed</div>
  914. <div class="swal2-progress">
  915. <div class="swal2-progress-bar" role="progressbar" aria-valuenow="${progress}" aria-valuemin="0" aria-valuemax="100" style="width: ${progress}%;">
  916. </div>
  917. </div>`
  918. });
  919. }
  920.  
  921.  
  922. swal.close();
  923. var newJSON=[]
  924. if (exportMode) {
  925. updateLocation(selections,taggedLocs)
  926. successText = 'Tagging completed! Please save the map and refresh the page(The JSON data is also pasted to your clipboard)'
  927. }
  928. taggedLocs.forEach((loc)=>{
  929. newJSON.push({lat:loc.location.lat,
  930. lng:loc.location.lng,
  931. heading:loc.heading,
  932. pitch: loc.pitch !== undefined && loc.pitch !== null ? loc.pitch : 90,
  933. zoom: loc.zoom !== undefined && loc.zoom !== null ? loc.zoom : 0,
  934. panoId:loc.panoId,
  935. extra:{tags:loc.tags}
  936. })
  937. })
  938. GM_setClipboard(JSON.stringify(newJSON))
  939. Swal.fire({
  940. title: 'Success!',
  941. text: successText,
  942. icon: 'success',
  943. showCancelButton: true,
  944. confirmButtonColor: '#3085d6',
  945. cancelButtonColor: '#d33',
  946. confirmButtonText: 'OK'
  947. })
  948. } catch (error) {
  949. swal.close();
  950. Swal.fire('Error Tagging!', '','error');
  951. console.error('Error processing JSON data:', error);
  952. }
  953. }
  954.  
  955. }
  956.  
  957. function chunkArray(array, maxSize) {
  958. const result = [];
  959. for (let i = 0; i < array.length; i += maxSize) {
  960. result.push(array.slice(i, i + maxSize));
  961. }
  962. return result;
  963. }
  964.  
  965. function generateCheckboxHTML(tags) {
  966.  
  967. const half = Math.ceil(tags.length / 2);
  968. const firstHalf = tags.slice(0, half);
  969. const secondHalf = tags.slice(half);
  970.  
  971. return `
  972. <div style="display: flex; flex-wrap: wrap; gap: 10px; text-align: left;">
  973. <div style="flex: 1; min-width: 150px;">
  974. ${firstHalf.map((tag, index) => `
  975. <label style="display: block; margin-bottom: 12px; margin-left: 40px; font-size: 15px;" title="${tooltips[tag]}">
  976. <input type="checkbox" class="feature-checkbox" value="${tag}" /> <span style="font-size: 14px;">${tag}</span>
  977. </label>
  978. `).join('')}
  979. </div>
  980. <div style="flex: 1; min-width: 150px;">
  981. ${secondHalf.map((tag, index) => `
  982. <label style="display: block; margin-bottom: 12px; margin-left: 40px; font-size: 15px;" title="${tooltips[tag]}">
  983. <input type="checkbox" class="feature-checkbox" value="${tag}" /> <span style="font-size: 14px;">${tag}</span>
  984. </label>
  985. `).join('')}
  986. </div>
  987. <div style="flex: 1; min-width: 150px; margin-top: 12px; text-align: center;">
  988. <label style="display: block; font-size: 14px;">
  989. <input type="checkbox" class="feature-checkbox" id="selectAll" /> <span style="font-size: 16px;">Select All</span>
  990. </label>
  991. </div>
  992. </div>
  993. `;
  994. }
  995.  
  996. function showFeatureSelectionPopup() {
  997. const checkboxesHTML = generateCheckboxHTML(tagBox);
  998.  
  999. Swal.fire({
  1000. title: 'Select Features',
  1001. html: `
  1002. ${checkboxesHTML}
  1003. `,
  1004. icon: 'question',
  1005. showCancelButton: true,
  1006. showCloseButton: true,
  1007. allowOutsideClick: false,
  1008. confirmButtonColor: '#3085d6',
  1009. cancelButtonColor: '#d33',
  1010. confirmButtonText: 'Start Tagging',
  1011. cancelButtonText: 'Cancel',
  1012. didOpen: () => {
  1013. const selectAllCheckbox = Swal.getPopup().querySelector('#selectAll');
  1014. const featureCheckboxes = Swal.getPopup().querySelectorAll('.feature-checkbox:not(#selectAll)');
  1015.  
  1016. selectAllCheckbox.addEventListener('change', () => {
  1017. featureCheckboxes.forEach(checkbox => {
  1018. checkbox.checked = selectAllCheckbox.checked;
  1019. });
  1020. });
  1021.  
  1022.  
  1023. featureCheckboxes.forEach(checkbox => {
  1024. checkbox.addEventListener('change', () => {
  1025.  
  1026. const allChecked = Array.from(featureCheckboxes).every(checkbox => checkbox.checked);
  1027. selectAllCheckbox.checked = allChecked;
  1028. });
  1029. });
  1030. },
  1031. preConfirm: () => {
  1032. const selectedFeatures = [];
  1033. const featureCheckboxes = Swal.getPopup().querySelectorAll('.feature-checkbox:not(#selectAll)');
  1034.  
  1035. featureCheckboxes.forEach(checkbox => {
  1036. if (checkbox.checked) {
  1037. selectedFeatures.push(checkbox.value.toLowerCase());
  1038. }
  1039. });
  1040.  
  1041. return selectedFeatures;
  1042. }
  1043. }).then((result) => {
  1044. if (result.isConfirmed) {
  1045. const selectedFeatures = result.value;
  1046. handleSelectedFeatures(selectedFeatures);
  1047. } else if (result.dismiss === Swal.DismissReason.cancel) {
  1048. console.log('User canceled');
  1049. }
  1050. });
  1051. }
  1052.  
  1053. function handleSelectedFeatures(features) {
  1054. if (features.includes('elevation')) {
  1055. Swal.fire({
  1056. title: 'Set A Range For Elevation',
  1057. text: 'If you select "Cancel", the script will return the exact elevation for each location.',
  1058. icon: 'question',
  1059. showCancelButton: true,
  1060. showCloseButton: true,
  1061. allowOutsideClick: false,
  1062. confirmButtonColor: '#3085d6',
  1063. cancelButtonColor: '#d33',
  1064. confirmButtonText: 'Yes',
  1065. cancelButtonText: 'Cancel'
  1066. }).then((result) => {
  1067. if (result.isConfirmed) {
  1068. Swal.fire({
  1069. title: 'Define Range for Each Segment',
  1070. html: `
  1071. <label> <br>Enter range for each segment, separated by commas</br></label>
  1072. <textarea id="segmentRanges" class="swal2-textarea" placeholder="such as:-1-10,11-35"></textarea>
  1073. `,
  1074. icon: 'question',
  1075. showCancelButton: true,
  1076. showCloseButton: true,
  1077. allowOutsideClick: false,
  1078. focusConfirm: false,
  1079. preConfirm: () => {
  1080. const segmentRangesInput = document.getElementById('segmentRanges').value.trim();
  1081. if (!segmentRangesInput) {
  1082. Swal.showValidationMessage('Please enter range for each segment');
  1083. return false;
  1084. }
  1085. const segmentRanges = segmentRangesInput.split(',');
  1086. const validatedRanges = segmentRanges.map(range => {
  1087. const matches = range.trim().match(/^\s*(-?\d+)\s*-\s*(-?\d+)\s*$/);
  1088. if (matches) {
  1089. const min = Number(matches[1]);
  1090. const max = Number(matches[2]);
  1091. return { min, max };
  1092. } else {
  1093. Swal.showValidationMessage('Invalid range format. Please use format: minValue-maxValue');
  1094. return false;
  1095. }
  1096. });
  1097. return validatedRanges.filter(Boolean);
  1098. },
  1099. confirmButtonColor: '#3085d6',
  1100. cancelButtonColor: '#d33',
  1101. confirmButtonText: 'Yes',
  1102. cancelButtonText: 'Cancel',
  1103. inputValidator: (value) => {
  1104. if (!value.trim()) {
  1105. return 'Please enter range for each segment';
  1106. }
  1107. }
  1108. }).then((result) => {
  1109. if (result.isConfirmed) {
  1110. runScript(features, result.value);
  1111. } else {
  1112. Swal.showValidationMessage('You canceled input');
  1113. }
  1114. });
  1115. } else if (result.dismiss === Swal.DismissReason.cancel) {
  1116. runScript(features);
  1117. }
  1118. });
  1119. } else {
  1120. runScript(features);
  1121. }
  1122. }
  1123.  
  1124. function calSun(date,lat,lng){
  1125. if (lat && lng && date) {
  1126. const format_date = new Date(date);
  1127. const times = SunCalc.getTimes(format_date, lat, lng);
  1128. const sunsetTimestamp = Math.round(times.sunset.getTime() / 1000);
  1129. const sunriseTimestamp = Math.round(times.sunrise.getTime() / 1000);
  1130. const noonTimestamp = Math.round(times.solarNoon.getTime() / 1000);
  1131. return {
  1132. sunset: sunsetTimestamp,
  1133. sunrise: sunriseTimestamp,
  1134. noon: noonTimestamp,
  1135. };
  1136. }
  1137. }
  1138.  
  1139.  
  1140. async function getBrightness(panoId) {
  1141. 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`;
  1142.  
  1143. try {
  1144. const response = await fetch(url);
  1145. if (!response.ok) {
  1146. throw new Error(`Failed to fetch image: ${response.statusText}`);
  1147. }
  1148.  
  1149. const imageBlob = await response.blob();
  1150. const imageUrl = URL.createObjectURL(imageBlob);
  1151.  
  1152. const img = new Image();
  1153. img.src = imageUrl;
  1154.  
  1155.  
  1156. await new Promise((resolve) => {
  1157. img.onload = resolve;
  1158. });
  1159.  
  1160.  
  1161. const canvas = document.createElement('canvas');
  1162. canvas.width = img.width;
  1163. canvas.height = Math.floor(img.height*0.4);
  1164. const ctx = canvas.getContext('2d');
  1165. ctx.drawImage(img, 0, 0);
  1166.  
  1167.  
  1168. const imageData = ctx.getImageData(0, 0, canvas.width, canvas.height);
  1169. const data = imageData.data;
  1170.  
  1171.  
  1172. let totalBrightness = 0;
  1173. for (let i = 0; i < data.length; i += 4) {
  1174. const r = data[i];
  1175. const g = data[i + 1];
  1176. const b = data[i + 2];
  1177. const brightness = (r + g + b) / 3;
  1178. totalBrightness += brightness;
  1179. }
  1180.  
  1181. const averageBrightness = totalBrightness / (data.length / 4);
  1182.  
  1183.  
  1184. URL.revokeObjectURL(imageUrl);
  1185.  
  1186. return averageBrightness;
  1187.  
  1188. } catch (error) {
  1189. console.error('Error:', error);
  1190. return null;
  1191. }
  1192. }
  1193.  
  1194. var mainButton = document.createElement('button');
  1195. mainButton.textContent = 'Auto-Tag';
  1196. mainButton.id = 'main-button';
  1197. mainButton.style.position = 'fixed';
  1198. mainButton.style.right = '20px';
  1199. mainButton.style.bottom = '15px';
  1200. mainButton.style.borderRadius = '18px';
  1201. mainButton.style.padding = '5px 10px';
  1202. mainButton.style.border = 'none';
  1203. mainButton.style.color = 'white';
  1204. mainButton.style.cursor = 'pointer';
  1205. mainButton.style.backgroundColor = '#4CAF50';
  1206. mainButton.addEventListener('click', showFeatureSelectionPopup);
  1207. document.body.appendChild(mainButton)
  1208.  
  1209. })();