Geoguessr Map-Making Auto-Tag

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

当前为 2025-06-19 提交的版本,查看 最新版本

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