Greasy Fork 还支持 简体中文。

Geoguessr Map-Making Auto-Tag

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

目前為 2024-10-23 提交的版本,檢視 最新版本

  1. // ==UserScript==
  2. // @name Geoguessr Map-Making Auto-Tag
  3. // @namespace https://greasyfork.org/users/1179204
  4. // @version 3.88.6
  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. 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', 'Generation', 'Elevation','Brightness','Driving Direction','Pan to Sun','Reset Heading','Update','Detect','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 capture in format yyyy',
  28. 'Month': 'Month of pano capture in format yy-mm',
  29. 'Day': 'Specific date of pano capture in format yyyy-mm-dd',
  30. 'Time': 'Exact time of pano capture with optional time range description, e.g., 09:35:21 marked as Morning',
  31. 'Country': 'Country of pano capture location (Google data)',
  32. 'Subdivision': 'Primary administrative subdivision of street view location',
  33. 'Generation': 'Camera generation of the street view, categorized as Gen1, Gen2orGen3, Gen3, Gen4, Shitcam',
  34. 'Elevation': 'Elevation of street view location (Google data)',
  35. 'Type': 'Type of pano, categorized as Official, Unofficial, Trekker (may include floor ID if available)',
  36. 'Driving Direction': 'Absolute driving direction of street view vehicle',
  37. 'Reset Heading': 'Reset heading to default driving direction of street view vehicle',
  38. 'Fix': 'Fix broken locs by updating to latest coverage or searching for specific coverage based on saved date from map-making',
  39. 'Update': 'Update pano to latest coverage or based on saved date from map-making, effective only for locs with panoID',
  40. 'Detect': 'Detect pano that is about to be removed and mark it as "Dangerous" ',
  41. 'Sun':'Detect whether it is sunset or sunrise coverage(effective only for defalut coverage)',
  42. 'Pan to Sun':'Make pano heading to sun(moon),effective only for defalut coverage',
  43. 'Weather':'Weather type recorded by the weather station closest to the loc, with a accuracy of 10mins(effective only for defalut coverage)'
  44. };
  45.  
  46. const weatherCodeMap = {
  47. 0: 'Clear sky',
  48. 1: 'Mainly clear',
  49. 2: 'Partly cloudy',
  50. 3: 'Mostly cloudy',
  51. 4: 'Overcast',
  52. 61:'Slight Rain',
  53. 63:'Moderate Rain',
  54. 65:'Heavy Rain',
  55. 51:'Light Drizzle',
  56. 53:'Moderate Drizzle',
  57. 55:'Dense Drizzle',
  58. 77:'Snow',
  59. 85:'Slight Snow',
  60. 86:'Heavy Snow',
  61. };
  62.  
  63. function deepClone(obj) {
  64. if (obj === null || typeof obj !== 'object') {
  65. return obj;
  66. }
  67.  
  68. const datePattern = /^(\d{4}-\d{2}-\d{2}T\d{2}:\d{2}:\d{2}([.,]\d{1,3})?Z?)$/;
  69.  
  70. if (Array.isArray(obj)) {
  71. return obj.map(item => deepClone(item));
  72. }
  73.  
  74. if (obj instanceof Date) {
  75. return new Date(obj.getTime());
  76. }
  77.  
  78. if (typeof obj === 'object') {
  79. const clonedObj = {};
  80. for (const key in obj) {
  81. if (obj.hasOwnProperty(key)) {
  82. if (typeof obj[key] === 'string' && datePattern.test(obj[key])) {
  83. clonedObj[key] = new Date(obj[key]);
  84. } else {
  85. clonedObj[key] = deepClone(obj[key]);
  86. }
  87. }
  88. }
  89. return clonedObj;
  90. }
  91.  
  92. return obj;
  93. }
  94.  
  95. function getSelection() {
  96. const editor = unsafeWindow.editor;
  97. if (editor) {
  98. const selectedLocs = editor.selections;
  99. const selections = deepClone(
  100. selectedLocs.flatMap(selection => selection.locations)
  101. );
  102. return selections;
  103. }
  104. }
  105.  
  106. function updateLocation(o,n) {
  107. const editor=unsafeWindow.editor
  108. if (editor){
  109. editor.removeLocations(o)
  110. editor.importLocations(n)
  111. }
  112. }
  113.  
  114. function findRange(elevation, ranges) {
  115. for (let i = 0; i < ranges.length; i++) {
  116. const range = ranges[i];
  117. if (elevation >= range.min && elevation <= range.max) {
  118. return `${range.min}-${range.max}m`;
  119. }
  120. }
  121. if (!elevation) {
  122. return 'noElevation';
  123. }
  124. return `${JSON.stringify(elevation)}m`;
  125. }
  126.  
  127. async function runScript(tags,sR) {
  128. let taggedLocs=[]
  129. let exportMode,selections,fixStrategy
  130.  
  131. if (tags.length<1){
  132. swal.fire('Feature not found!', 'Please select at least one feature!','warning')
  133. return}
  134. if (tags.includes('fix')){
  135. const { value: fixOption,dismiss: fixDismiss } = await Swal.fire({
  136. title:'Fix Strategy',
  137. icon:'question',
  138. 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.',
  139. showCancelButton: true,
  140. showCloseButton:true,
  141. allowOutsideClick: false,
  142. confirmButtonColor: '#3085d6',
  143. cancelButtonColor: '#d33',
  144. confirmButtonText: 'Yes',
  145. cancelButtonText: 'No',
  146.  
  147. })
  148. if(fixOption)fixStrategy='exactly'
  149. else if(!fixOption&&fixDismiss==='cancel'){
  150. fixStrategy=null
  151. }
  152. else{
  153. return
  154. }
  155. };
  156.  
  157. const { value: option, dismiss: inputDismiss } = await Swal.fire({
  158. title: 'Export',
  159. 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.',
  160. icon: 'question',
  161. showCancelButton: true,
  162. showCloseButton: true,
  163. allowOutsideClick: false,
  164. confirmButtonColor: '#3085d6',
  165. cancelButtonColor: '#d33',
  166. confirmButtonText: 'Yes',
  167. cancelButtonText: 'Cancel'
  168. });
  169.  
  170. if (option) {
  171. exportMode = 'save'
  172. }
  173. else if (!selections && inputDismiss === 'cancel') {
  174. exportMode = false
  175. }
  176. else {
  177. return
  178. }
  179.  
  180. selections=getSelection()
  181.  
  182. if (!selections||selections.length<1){
  183. swal.fire('Selection not found!', 'Please select at least one location as selection!','warning')
  184. return
  185. }
  186.  
  187. var CHUNK_SIZE = 1200;
  188. if (tags.includes('time')){
  189. CHUNK_SIZE = 1000
  190. }
  191. var promises = [];
  192.  
  193. if(selections){
  194. if(selections.length>=1){processData(tags);}
  195. else{
  196. 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');}
  197. }else{Swal.fire('Error Parsing JSON Data!', 'The input JSON data is invaild or incorrectly formatted.','error');}
  198.  
  199. async function UE(t, e, s, d,r) {
  200. try {
  201. const u = `https://maps.googleapis.com/$rpc/google.internal.maps.mapsjs.v1.MapsJsInternalService/${t}`;
  202. let payload = createPayload(t, e,s,d,r);
  203.  
  204. const response = await fetch(u, {
  205. method: "POST",
  206. headers: {
  207. "content-type": "application/json+protobuf",
  208. "x-user-agent": "grpc-web-javascript/0.1"
  209. },
  210. body: payload,
  211. mode: "cors",
  212. credentials: "omit"
  213. });
  214.  
  215. if (!response.ok) {
  216. throw new Error(`HTTP error! status: ${response.status}`);
  217. } else {
  218. return await response.json();
  219. }
  220. } catch (error) {
  221. console.error(`There was a problem with the UE function: ${error.message}`);
  222. }
  223. }
  224.  
  225. function createPayload(mode,coorData,s,d,r) {
  226. let payload;
  227. if(!r)r=50 // default search radius
  228. if (mode === 'GetMetadata') {
  229. payload = [["apiv3",null,null,null,"US",null,null,null,null,null,[[0]]],["en","US"],[[[2,coorData]]],[[1,2,3,4,8,6]]];
  230. } else if (mode === 'SingleImageSearch') {
  231.  
  232. if(s&&d){
  233. 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]]]
  234. }else{
  235. payload =[["apiv3"],
  236. [[null,null,coorData.lat,coorData.lng],r],
  237. [null,["en","US"],null,null,null,null,null,null,[2],null,[[[2,true,2]]]], [[1,2,3,4,8,6]]];}
  238. } else {
  239. throw new Error("Invalid mode!");
  240. }
  241. return JSON.stringify(payload);
  242. }
  243.  
  244. function monthToTimestamp(m) {
  245.  
  246. const [year, month] = m.split('-');
  247.  
  248. const startDate =Math.round( new Date(year, month-1,1).getTime()/1000);
  249.  
  250. const endDate =Math.round( new Date(year, month, 1).getTime()/1000)-1;
  251.  
  252. return { startDate, endDate };
  253. }
  254.  
  255. async function binarySearch(c, start,end) {
  256. let capture
  257. let response
  258. while (end - start >= accuracy) {
  259. let mid= Math.round((start + end) / 2);
  260. response = await UE("SingleImageSearch", c, start,end,15);
  261. if (response&&response[0][2]== "Search returned no images." ){
  262. start=mid+start-end
  263. end=start-mid+end
  264. mid=Math.round((start+end)/2)
  265. } else {
  266. start=mid
  267. mid=Math.round((start+end)/2)
  268. }
  269. capture=mid
  270. }
  271.  
  272. return capture
  273. }
  274.  
  275. function getMetaData(svData) {
  276. let year = 'Year not found',month = 'Month not found'
  277. let panoType='unofficial'
  278. let subdivision='Subdivision not found'
  279. let defaultHeading=null
  280. if (svData) {
  281. if (svData.imageDate) {
  282. const matchYear = svData.imageDate.match(/\d{4}/);
  283. if (matchYear) {
  284. year = matchYear[0];
  285. }
  286.  
  287. const matchMonth = svData.imageDate.match(/-(\d{2})/);
  288. if (matchMonth) {
  289. month = matchMonth[1];
  290. }
  291. }
  292. if (svData.copyright.includes('Google')) {
  293. panoType = 'Official';
  294. }
  295. if (svData.tiles&&svData.tiles&&svData.tiles.originHeading){
  296. defaultHeading=svData.tiles.originHeading
  297. }
  298. if(svData.location.description){
  299. let parts = svData.location.description.split(',');
  300. if(parts.length > 1){
  301. subdivision = parts[parts.length-1].trim();
  302. } else {
  303. subdivision = svData.location.description;
  304. }
  305. }
  306. return [year,month,panoType,subdivision,defaultHeading]
  307. }
  308. else{
  309. return null
  310. }
  311. }
  312.  
  313. function extractDate(array) {
  314. let year, month;
  315.  
  316. array.forEach(element => {
  317. const yearRegex1 = /^(\d{2})-(\d{2})$/; // Matches yy-mm
  318. const yearRegex2 = /^(\d{4})-(\d{2})$/; // Matches yyyy-mm
  319. const yearRegex3 = /^(\d{4})$/; // Matches yyyy
  320. const monthRegex1 = /^(\d{2})$/; // Matches mm
  321. const monthRegex2 = /^(January|February|March|April|May|June|July|August|September|October|November|December)$/i; // Matches month names
  322.  
  323. if (!month && yearRegex1.test(element)) {
  324. const match = yearRegex1.exec(element);
  325. year = parseInt(match[1]) + 2000; // Convert to full year
  326. month = parseInt(match[2]);
  327. }
  328.  
  329. if (!month && yearRegex2.test(element)) {
  330. const match = yearRegex2.exec(element);
  331. year = parseInt(match[1]);
  332. month = parseInt(match[2]);
  333. }
  334.  
  335. if (!year && yearRegex3.test(element)) {
  336. year = parseInt(element);
  337. }
  338.  
  339. if (!month && monthRegex1.test(element)) {
  340. month = parseInt(element);
  341. }
  342.  
  343. if (!month && monthRegex2.test(element)) {
  344. const months = {
  345. "January": 1, "February": 2, "March": 3, "April": 4,
  346. "May": 5, "June": 6, "July": 7, "August": 8,
  347. "September": 9, "October": 10, "November": 11, "December": 12
  348. };
  349. month = months[element];
  350. }
  351. });
  352. return {year,month}
  353. }
  354.  
  355. function getDirection(heading) {
  356. if (typeof heading !== 'number' || heading < 0 || heading >= 360) {
  357. return 'Unknown direction';
  358. }
  359. const directions = [
  360. { name: 'North', range: [337.5, 22.5] },
  361. { name: 'Northeast', range: [22.5, 67.5] },
  362. { name: 'East', range: [67.5, 112.5] },
  363. { name: 'Southeast', range: [112.5, 157.5] },
  364. { name: 'South', range: [157.5, 202.5] },
  365. { name: 'Southwest', range: [202.5, 247.5] },
  366. { name: 'West', range: [247.5, 292.5] },
  367. { name: 'Northwest', range: [292.5, 337.5] }
  368. ];
  369.  
  370. for (const direction of directions) {
  371. const [start, end] = direction.range;
  372. if (start <= end) {
  373. if (heading >= start && heading < end) {
  374. return direction.name;
  375. }
  376. } else {
  377. if (heading >= start || heading < end) {
  378. return direction.name;
  379. }
  380. }
  381. }
  382.  
  383. return 'Unknown direction';
  384. }
  385.  
  386. function getGeneration(svData,country) {
  387. if (svData&&svData.tiles) {
  388. if (svData.tiles.worldSize.height === 1664) { // Gen 1
  389. return 'Gen1';
  390. } else if (svData.tiles.worldSize.height === 6656) { // Gen 2 or 3
  391.  
  392. let lat;
  393. for (let key in svData.Sv) {
  394. lat = svData.Sv[key].lat;
  395. break;
  396. }
  397.  
  398. let date;
  399. if (svData.imageDate) {
  400. date = new Date(svData.imageDate);
  401. } else {
  402. date = 'nodata';
  403. }
  404.  
  405. if (date!=='nodata'&&((country === 'BD' && (date >= new Date('2021-04'))) ||
  406. (country === 'EC' && (date >= new Date('2022-03'))) ||
  407. (country === 'FI' && (date >= new Date('2020-09'))) ||
  408. (country === 'IN' && (date >= new Date('2021-10'))) ||
  409. (country === 'LK' && (date >= new Date('2021-02'))) ||
  410. (country === 'KH' && (date >= new Date('2022-10'))) ||
  411. (country === 'LB' && (date >= new Date('2021-05'))) ||
  412. (country === 'NG' && (date >= new Date('2021-06'))) ||
  413. (country === 'ST') ||
  414. (country === 'US' && lat > 52 && (date >= new Date('2019-01'))))) {
  415. return 'Shitcam';
  416. }
  417.  
  418. let gen2Countries = ['AU', 'BR', 'CA', 'CL', 'JP', 'GB', 'IE', 'NZ', 'MX', 'RU', 'US', 'IT', 'DK', 'GR', 'RO',
  419. 'PL', 'CZ', 'CH', 'SE', 'FI', 'BE', 'LU', 'NL', 'ZA', 'SG', 'TW', 'HK', 'MO', 'MC', 'SM',
  420. 'AD', 'IM', 'JE', 'FR', 'DE', 'ES', 'PT'];
  421. if (gen2Countries.includes(country)) {
  422.  
  423. return 'Gen2or3';
  424. }
  425. else{
  426. return 'Gen3';}
  427. }
  428. else if(svData.tiles.worldSize.height === 8192){
  429. return 'Gen4';
  430. }
  431. }
  432. return 'Unknown';
  433. }
  434.  
  435. async function getLocal(coord, timestamp) {
  436. const systemTimezoneOffset = -new Date().getTimezoneOffset() * 60;
  437.  
  438. try {
  439. var offset_hours
  440. const timezone=await GeoTZ.find(coord[0],coord[1])
  441.  
  442. const offset = await GeoTZ.toOffset(timezone);
  443.  
  444. if(offset){
  445. offset_hours=parseInt(offset/60)
  446. }
  447. else if (offset===0) offset_hours=0
  448. const offsetDiff = systemTimezoneOffset -offset_hours*3600;
  449. const convertedTimestamp = Math.round(timestamp - offsetDiff);
  450. return convertedTimestamp;
  451. } catch (error) {
  452. throw error;
  453. }
  454. }
  455.  
  456. async function getWeather(coordinate, timestamp) {
  457. var hours,weatherCodes
  458. const date = new Date(timestamp * 1000);
  459. const formatted_date = date.toISOString().split('T')[0]
  460. try {
  461. 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`;
  462. const response = await fetch(url);
  463. const data = await response.json();
  464. hours = data.hourly.time;
  465. weatherCodes = data.hourly.weather_code;
  466.  
  467. const targetHour = new Date(timestamp * 1000).getHours();
  468. let closestHourIndex = 0;
  469. let minDiff = Infinity;
  470.  
  471. for (let i = 0; i < hours.length; i++) {
  472. const hour = new Date(hours[i]).getHours();
  473. const diff = Math.abs(hour - targetHour);
  474.  
  475. if (diff < minDiff) {
  476. minDiff = diff;
  477. closestHourIndex = i;
  478. }
  479. }
  480.  
  481. const weatherCode = weatherCodes[closestHourIndex];
  482. const weatherDescription = weatherCodeMap[weatherCode] || 'Unknown weather code';
  483. return weatherDescription;
  484.  
  485. } catch (error) {
  486. console.error('Error fetching weather data:', error);
  487. return 'Network request failed'
  488. }
  489. }
  490.  
  491. async function processCoord(coord, tags, svData,ccData) {
  492. var panoYear,panoMonth
  493. if (tags.includes(('fix')||('update')||('detect'))){
  494. if (coord.panoDate){
  495. panoYear=parseInt(coord.panoDate.toISOString().substring(0,4))
  496. panoMonth=parseInt(coord.panoDate.toISOString().substring(5,7))
  497. }
  498. else if(svData&&svData.imageDate){
  499. panoYear=parseInt(svData.imageDate.substring(0,4))
  500. panoMonth=parseInt(svData.imageDate.substring(5,7))
  501.  
  502. }
  503. else{
  504. panoYear=parseInt(extractDate(coord.tags).year)
  505. panoMonth=parseInt(extractDate(coord.tags).month)
  506. }
  507. }
  508. try{
  509. if (svData||ccData){
  510. let meta=getMetaData(svData)
  511. let yearTag=meta[0]
  512. let monthTag=parseInt(meta[1])
  513. let typeTag=meta[2]
  514. let subdivisionTag=meta[3]
  515. let countryTag,elevationTag
  516. let genTag,trekkerTag,floorTag,driDirTag,weatherTag
  517. let dayTag,timeTag,exactTime,timeRange
  518.  
  519. if(monthTag){monthTag=months[monthTag-1]}
  520. //if(monthTag) monthTag=yearTag.slice(-2)+'-'+(monthTag.toString())
  521. if (!monthTag){monthTag='Month not found'}
  522.  
  523. var date=monthToTimestamp(svData.imageDate)
  524.  
  525. if(tags.includes('day')||tags.includes('time')||tags.includes('sun')||tags.includes('weather')||tags.includes('pan to sun')){
  526. const initialSearch=await UE('SingleImageSearch',{lat:coord.location.lat,lng:coord.location.lng},date.startDate,date.endDate,15)
  527. if (initialSearch){
  528. if (initialSearch.length!=3)exactTime=null;
  529. else{
  530. if(!tags.includes('day')) accuracy=18000
  531. if(tags.includes('weather')) accuracy=600
  532. if (tags.includes('sun')) accuracy=300
  533. if (tags.includes('pan to sun')) accuracy=300
  534. if (tags.includes('time')) accuracy=60
  535. exactTime=await binarySearch({lat:coord.location.lat,lng:coord.location.lng}, date.startDate,date.endDate)
  536. }
  537. }
  538. }
  539.  
  540. if(!exactTime){dayTag='Day not found'
  541. timeTag='Time not found'}
  542. else{
  543.  
  544. if (tags.includes('day')){
  545. const currentDate = new Date();
  546. const currentOffset =-(currentDate.getTimezoneOffset())*60
  547. const dayOffset = currentOffset-Math.round((coord.location.lng / 15) * 3600);
  548. const LocalDay=new Date(Math.round(exactTime-dayOffset)*1000)
  549. dayTag = LocalDay.toISOString().split('T')[0];
  550. }
  551.  
  552. if(tags.includes('time')) {
  553.  
  554. var localTime=await getLocal([coord.location.lat,coord.location.lng],exactTime)
  555. var timeObject=new Date(localTime*1000)
  556. timeTag =`${timeObject.getHours().toString().padStart(2, '0')}:${timeObject.getMinutes().toString().padStart(2, '0')}:${timeObject.getSeconds().toString().padStart(2, '0')}`;
  557. var hour = timeObject.getHours();
  558.  
  559. if (hour < 11) {
  560. timeRange = 'Morning';
  561. } else if (hour >= 11 && hour < 13) {
  562. timeRange = 'Noon';
  563. } else if (hour >= 13 && hour < 17) {
  564. timeRange = 'Afternoon';
  565. } else if(hour >= 17 && hour < 19) {
  566. timeRange = 'Dusk';
  567. }
  568. else{
  569. timeRange = 'Night';
  570. }
  571. }
  572.  
  573. if (tags.includes('sun')){
  574. const utcDate=new Date(exactTime*1000)
  575. const sunData=calSun(utcDate.toISOString(),coord.location.lat,coord.location.lng)
  576. if(sunData){
  577. if (exactTime>=(sunData.sunset-30*60)&&exactTime<=(sunData.sunset+30*60)){
  578. coord.tags.push('Sunset')
  579. }
  580. else if (exactTime>=(sunData.sunset-90*60)&&exactTime<=(sunData.sunset+90*60)){
  581. coord.tags.push('Sunset(check)')
  582. }
  583. else if (exactTime>=(sunData.sunrise-30*60)&&exactTime<=(sunData.sunrise+30*60)){
  584. coord.tags.push('Sunrise')
  585. }
  586. else if (exactTime>=(sunData.sunrise-90*60)&&exactTime<=(sunData.sunrise+90*60)){
  587. coord.tags.push('Sunrise(check)')
  588. }
  589. else if (exactTime>=(sunData.noon-30*60)&&exactTime<=(sunData.noon+30*60)){
  590. coord.tags.push('Noon')
  591. }
  592. }
  593. }
  594.  
  595. if (tags.includes('pan to sun')){
  596. const date = new Date(exactTime * 1000);
  597. const position = SunCalc.getPosition(date, coord.location.lat, coord.location.lng);
  598.  
  599. const altitude = position.altitude;
  600. const azimuth = position.azimuth;
  601.  
  602. const altitudeDegrees = altitude * (180 / Math.PI);
  603. const azimuthDegrees = azimuth * (180 / Math.PI);
  604. if(azimuthDegrees&&altitudeDegrees){
  605. if (altitudeDegrees<0){
  606. const moonPosition = SunCalc.getMoonPosition(date, coord.location.lat, coord.location.lng);
  607. const moon_altitude = moonPosition.altitude;
  608. const moon_azimuth = moonPosition.azimuth;
  609. const moon_altitudeDegrees = moon_altitude * (180 / Math.PI);
  610. const moon_azimuthDegrees = moon_azimuth * (180 / Math.PI);
  611. coord.heading=moon_azimuthDegrees+180
  612. coord.pitch=moon_altitudeDegrees
  613. coord.zoom=2
  614. coord.tags.push('pan to moon')
  615. }
  616. else{
  617. coord.heading=azimuthDegrees+180
  618. coord.pitch=altitudeDegrees
  619. coord.tags.push('pan to sun')
  620. }
  621. }
  622. }
  623.  
  624. if(tags.includes('weather')) {
  625. weatherTag=await getWeather(coord.location,exactTime)
  626. if(weatherTag) coord.tags.push(weatherTag)
  627. }
  628. }
  629.  
  630. try {if (ccData.length!=3) ccData=ccData[1][0]
  631. else ccData=ccData[1]
  632. }
  633.  
  634. catch (error) {
  635. ccData=null
  636. }
  637.  
  638. if (ccData){
  639. try{
  640. countryTag = ccData[5][0][1][4]}
  641. catch(error){
  642. countryTag=null
  643. }
  644. try{
  645. elevationTag=ccData[5][0][1][1][0]}
  646. catch(error){
  647. elevationTag=null
  648. }
  649. try{
  650. driDirTag=ccData[5][0][1][2][0]}
  651. catch(error){
  652. driDirTag=null
  653. }
  654. try{
  655. trekkerTag=ccData[6][5]}
  656. catch(error){
  657. trekkerTag=null
  658. }
  659. try{
  660. floorTag=ccData[5][0][1][3][2][0]
  661. }
  662. catch(error){
  663. floorTag=null
  664. }
  665. if (tags.includes('detect')){
  666. const defaultDate=3
  667. }
  668. }
  669.  
  670. if (trekkerTag){
  671. trekkerTag=trekkerTag.toString()
  672. if( trekkerTag.includes('scout')){
  673. trekkerTag='trekker'
  674. }
  675. else{
  676. trekkerTag=null
  677. }}
  678.  
  679. if(elevationTag){
  680. elevationTag=Math.round(elevationTag*100)/100
  681. if(sR){
  682. elevationTag=findRange(elevationTag,sR)
  683. }
  684. else{
  685. elevationTag=elevationTag.toString()+'m'
  686. }
  687. }
  688. if(driDirTag){
  689. driDirTag=getDirection(parseFloat(driDirTag))
  690. }
  691. else{
  692. driDirTag='Driving direction not found'
  693. }
  694. if (!countryTag)countryTag='Country not found'
  695. if (!elevationTag)elevationTag='Elevation not found'
  696.  
  697. if (tags.includes('generation')&&typeTag=='Official'&&countryTag){
  698. genTag = getGeneration(svData,countryTag)
  699. coord.tags.push(genTag)}
  700.  
  701. if (tags.includes('year'))coord.tags.push(yearTag)
  702.  
  703. if (tags.includes('month'))coord.tags.push(monthTag)
  704.  
  705. if (tags.includes('day'))coord.tags.push(dayTag)
  706.  
  707. if (tags.includes('time'))coord.tags.push(timeTag)
  708.  
  709. if (tags.includes('time')&&timeRange)coord.tags.push(timeRange)
  710.  
  711. if (tags.includes('type'))coord.tags.push(typeTag)
  712.  
  713. if (tags.includes('driving direction'))coord.tags.push(driDirTag)
  714.  
  715. if (tags.includes('type')&&trekkerTag&&typeTag=='Official')coord.tags.push('trekker')
  716.  
  717. if (tags.includes('type')&&floorTag&&typeTag=='Official')coord.tags.push(floorTag)
  718.  
  719. if (tags.includes('country'))coord.tags.push(countryTag)
  720.  
  721. if (tags.includes('subdivision')&&typeTag=='Official')coord.tags.push(subdivisionTag)
  722.  
  723. if (tags.includes('elevation'))coord.tags.push(elevationTag)
  724.  
  725. if (tags.includes('reset heading')){
  726. if(meta[4]) coord.heading=meta[4]
  727. }
  728.  
  729. if (tags.includes('update')){
  730. try{
  731. const resultPano=await UE('SingleImageSearch',{lat: coord.location.lat, lng: coord.location.lng},null,null,50)
  732. const updatedPnaoId=resultPano[1][1][1]
  733. const updatedYear=resultPano[1][6][7][0]
  734. const updatedMonth=resultPano[1][6][7][1]
  735. if (coord.panoId){
  736. if (updatedPnaoId&&updatedPnaoId!=coord.panoId) {
  737. if(panoYear!=updatedYear||panoMonth!=updatedMonth){
  738. coord.panoId=updatedPnaoId
  739. coord.tags.push('Updated')}
  740. else{
  741. coord.panoId=updatedPnaoId
  742. coord.tags.push('Copyright changed')
  743. }
  744. }
  745. }
  746. else{
  747. if (panoYear&&panoMonth&&updatedYear&&updatedMonth){
  748. if(panoYear!=updatedYear||panoMonth!=updatedMonth){
  749. coord.panoId=updatedPnaoId
  750. coord.tags.push('Updated')
  751. }
  752. }
  753. else{
  754. coord.panoId=svData.location.pano
  755. coord.tags.push('PanoId is added')
  756. }
  757. }
  758. }
  759. catch (error){
  760. coord.tags.push('Failed to update')
  761. }
  762. }
  763. }
  764. }
  765. catch (error) {
  766. if(!tags.includes('fix')&&!tags.includes('update'))coord.tags.push('Pano not found');
  767.  
  768. else if (tags.includes('update')){
  769. try{
  770. const resultPano=await UE('SingleImageSearch',{lat: coord.location.lat, lng: coord.location.lng},null,null,50)
  771. const updatedPnaoId=resultPano[1][1][1]
  772. const updatedYear=resultPano[1][6][7][0]
  773. const updatedMonth=resultPano[1][6][7][1]
  774. coord.panoId=updatedPnaoId
  775. coord.location.lat=resultPano[1][5][0][1][0][2]
  776. coord.location.lng=resultPano[1][5][0][1][0][3]
  777. }
  778. catch (error){
  779. coord.tags.push('Failed to update')
  780. }
  781. }
  782. else{
  783. var fixState
  784. try{
  785. const resultPano=await UE('SingleImageSearch',{lat: coord.location.lat, lng: coord.location.lng},null,null,15)
  786. if(fixStrategy){
  787. const panos=resultPano[1][5][0][8]
  788. for(const pano of panos){
  789. if(pano[1][0]===panoYear&&pano[1][1]===panoMonth){
  790. const panoIndex=pano[0]
  791. const fixedPanoId=resultPano[1][5][0][3][0][panoIndex][0][1]
  792. coord.panoId=fixedPanoId
  793. coord.location.lat=resultPano[1][5][0][1][0][2]
  794. coord.location.lng=resultPano[1][5][0][1][0][3]
  795. fixState=true
  796. }
  797. }
  798. }
  799. else{
  800. coord.panoId=resultPano[1][1][1]
  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. catch (error){
  808. fixState=null
  809. }
  810. if (!fixState)coord.tags.push('Failed to fix')
  811. else coord.tags.push('Fixed')
  812.  
  813. }
  814. }
  815. if (coord.tags) { coord.tags = Array.from(new Set(coord.tags))}
  816. taggedLocs.push(coord);
  817. }
  818.  
  819. async function processChunk(chunk, tags) {
  820. var service = new google.maps.StreetViewService();
  821. var panoSource= google.maps.StreetViewSource.GOOGLE
  822. var promises = chunk.map(async coord => {
  823. let panoId = coord.panoId;
  824. let latLng = {lat: coord.location.lat, lng: coord.location.lng};
  825. let svData;
  826. let ccData;
  827. if ((panoId || latLng)) {
  828. if(tags!=['country']&&tags!=['elevation']&&tags!=['detect']){
  829. svData = await getSVData(service, panoId ? {pano: panoId} : {location: latLng, radius: 50,source:panoSource});}
  830. }
  831.  
  832. if (tags.includes('generation')||('country')||('elevation')||('type')||('driving direction')) {
  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. function findClosestTime(year, month, lat, lng, heading, pitch) {
  1136. const targetAzimuth = (heading - 180) / (180 / Math.PI);
  1137. const targetAltitude = pitch / (180 / Math.PI);
  1138.  
  1139. const startDate = new Date(year, month - 1, 1);
  1140. const endDate = new Date(year, month, 0);
  1141.  
  1142. let closestDate = null;
  1143. let minDifference = Infinity;
  1144.  
  1145. for (let day = new Date(startDate); day <= endDate; day.setMinutes(day.getMinutes() + 1)) {
  1146. const sunPosition = SunCalc.getPosition(day, lat, lng);
  1147.  
  1148. const azimuthDiff = Math.abs(targetAzimuth - sunPosition.azimuth);
  1149. const altitudeDiff = Math.abs(targetAltitude - sunPosition.altitude);
  1150. const totalDifference = azimuthDiff + altitudeDiff;
  1151.  
  1152. if (totalDifference < minDifference) {
  1153. minDifference = totalDifference;
  1154. closestDate = new Date(day);
  1155. }
  1156. }
  1157.  
  1158. return closestDate;
  1159. }
  1160.  
  1161. async function getBrightness(panoId) {
  1162. 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`;
  1163.  
  1164. try {
  1165. const response = await fetch(url);
  1166. if (!response.ok) {
  1167. throw new Error(`Failed to fetch image: ${response.statusText}`);
  1168. }
  1169.  
  1170. const imageBlob = await response.blob();
  1171. const imageUrl = URL.createObjectURL(imageBlob);
  1172.  
  1173. const img = new Image();
  1174. img.src = imageUrl;
  1175.  
  1176.  
  1177. await new Promise((resolve) => {
  1178. img.onload = resolve;
  1179. });
  1180.  
  1181.  
  1182. const canvas = document.createElement('canvas');
  1183. canvas.width = img.width;
  1184. canvas.height = Math.floor(img.height*0.4);
  1185. const ctx = canvas.getContext('2d');
  1186. ctx.drawImage(img, 0, 0);
  1187.  
  1188.  
  1189. const imageData = ctx.getImageData(0, 0, canvas.width, canvas.height);
  1190. const data = imageData.data;
  1191.  
  1192.  
  1193. let totalBrightness = 0;
  1194. for (let i = 0; i < data.length; i += 4) {
  1195. const r = data[i];
  1196. const g = data[i + 1];
  1197. const b = data[i + 2];
  1198. const brightness = (r + g + b) / 3;
  1199. totalBrightness += brightness;
  1200. }
  1201.  
  1202. const averageBrightness = totalBrightness / (data.length / 4);
  1203.  
  1204.  
  1205. URL.revokeObjectURL(imageUrl);
  1206.  
  1207. return averageBrightness;
  1208.  
  1209. } catch (error) {
  1210. console.error('Error:', error);
  1211. return null;
  1212. }
  1213. }
  1214.  
  1215. function calculateFOV(zoom) {
  1216. const pi = Math.PI;
  1217. const argument = (3 / 4) * Math.pow(2, 1 - zoom);
  1218. const radians = Math.atan(argument);
  1219. const degrees = (360 / pi) * radians;
  1220. return degrees;
  1221. }
  1222. function createPayload(mode,coorData,s,d,r) {
  1223. let payload;
  1224. if(!r)r=30 // default search radius
  1225. if (mode === 'GetMetadata') {
  1226. payload = [["apiv3",null,null,null,"US",null,null,null,null,null,[[0]]],["en","US"],[[[2,coorData]]],[[1,2,3,4,8,6]]];
  1227. } else if (mode === 'SingleImageSearch') {
  1228.  
  1229. if(s&&d){
  1230. 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]]]
  1231. }else{
  1232. payload =[["apiv3"],
  1233. [[null,null,coorData.lat,coorData.lng],r],
  1234. [null,["en","US"],null,null,null,null,null,null,[2],null,[[[2,true,2]]]], [[1,2,3,4,8,6]]];}
  1235. } else {
  1236. throw new Error("Invalid mode!");
  1237. }
  1238. return JSON.stringify(payload);
  1239. }
  1240. async function binarySearch(c,start,end){
  1241. let capture
  1242. let response
  1243. while (end - start >= accuracy) {
  1244. let mid= Math.round((start + end) / 2);
  1245. response = await UE("SingleImageSearch", c, start,end,10);
  1246. if (response&&response[0][2]== "Search returned no images." ){
  1247. start=mid+start-end
  1248. end=start-mid+end
  1249. mid=Math.round((start+end)/2)
  1250. } else {
  1251. start=mid
  1252. mid=Math.round((start+end)/2)
  1253. }
  1254. capture=mid
  1255. }
  1256.  
  1257. return capture
  1258. }
  1259. async function UE(t, e, s, d,r) {
  1260. try {
  1261. const u = `https://maps.googleapis.com/$rpc/google.internal.maps.mapsjs.v1.MapsJsInternalService/${t}`;
  1262. let payload = createPayload(t, e,s,d,r);
  1263.  
  1264. const response = await fetch(u, {
  1265. method: "POST",
  1266. headers: {
  1267. "content-type": "application/json+protobuf",
  1268. "x-user-agent": "grpc-web-javascript/0.1"
  1269. },
  1270. body: payload,
  1271. mode: "cors",
  1272. credentials: "omit"
  1273. });
  1274.  
  1275. if (!response.ok) {
  1276. throw new Error(`HTTP error! status: ${response.status}`);
  1277. } else {
  1278. return await response.json();
  1279. }
  1280. } catch (error) {
  1281. console.error(`There was a problem with the UE function: ${error.message}`);
  1282. }
  1283. }
  1284. function monthToTimestamp(m) {
  1285. m=m.toISOString().substring(0,7)
  1286. const [year, month] = m.split('-');
  1287.  
  1288. const startDate =Math.round( new Date(year, month-1,1).getTime()/1000);
  1289.  
  1290. const endDate =Math.round( new Date(year, month, 1).getTime()/1000)-1;
  1291.  
  1292. return { startDate, endDate };
  1293. }
  1294.  
  1295. let onKeyDown = async (e) => {
  1296. if (e.key === 'l' || e.key === 'L') {
  1297. e.stopImmediatePropagation();
  1298. const pano=unsafeWindow.editor.currentLocation
  1299. const heading=pano.updatedProps.heading
  1300. const pitch=pano.updatedProps.pitch
  1301. const panoDate=pano.updatedProps.panoDate
  1302. const year = panoDate.getFullYear();
  1303. const month = panoDate.getMonth()+1
  1304. const lat=pano.updatedProps.location.lat
  1305. const lng=pano.updatedProps.location.lng
  1306. const closeTime=findClosestTime(year, month, lat, lng,heading,pitch)
  1307. console.log(closeTime.toLocaleString())
  1308. }
  1309.  
  1310. if (e.key === 'G' || e.key === 'g') {
  1311. const sv=unsafeWindow.streetView
  1312. const pano=unsafeWindow.editor.currentLocation
  1313. const lat=pano.updatedProps.location.lat
  1314. const lng=pano.updatedProps.location.lng
  1315. e.stopImmediatePropagation();
  1316. const date=monthToTimestamp(pano.updatedProps.panoDate)
  1317. var exactTime
  1318. accuracy=300
  1319. exactTime=await binarySearch({lat:lat,lng:lng}, date.startDate,date.endDate)
  1320. const exactDate = new Date(exactTime * 1000);
  1321. const moonPosition = SunCalc.getMoonPosition(exactDate,lat, lng);
  1322. const moon_altitude = moonPosition.altitude;
  1323. const moon_azimuth = moonPosition.azimuth;
  1324. const moon_altitudeDegrees = moon_altitude * (180 / Math.PI);
  1325. const moon_azimuthDegrees = moon_azimuth * (180 / Math.PI);
  1326. sv.setPov({heading:moon_azimuthDegrees+180,pitch:moon_altitudeDegrees})
  1327. sv.setZoom(3)
  1328.  
  1329. }
  1330. }
  1331.  
  1332. document.addEventListener("keydown", onKeyDown);
  1333.  
  1334.  
  1335. var mainButton = document.createElement('button');
  1336. mainButton.textContent = 'Auto-Tag';
  1337. mainButton.id = 'main-button';
  1338. mainButton.style.position = 'fixed';
  1339. mainButton.style.right = '20px';
  1340. mainButton.style.bottom = '15px';
  1341. mainButton.style.borderRadius = '18px';
  1342. mainButton.style.fontSize = '15px';
  1343. mainButton.style.padding = '10px 20px';
  1344. mainButton.style.border = 'none';
  1345. mainButton.style.color = 'white';
  1346. mainButton.style.cursor = 'pointer';
  1347. mainButton.style.backgroundColor = '#4CAF50';
  1348. mainButton.addEventListener('click', showFeatureSelectionPopup);
  1349. document.body.appendChild(mainButton)
  1350.  
  1351. })();