Geoguessr Map-Making Auto-Tag

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

当前为 2024-11-17 提交的版本,查看 最新版本

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