- // ==UserScript==
- // @name Restore Google Maps Button to Search Bar
- // @namespace http://tampermonkey.net/
- // @version 1.0
- // @description Restores the "Maps" button to the Google search bar.
- // @author n1ghtmare_13
- // @match *://www.google.com/*
- // @match *://www.google.pl/*
- // @grant none
- // @run-at document-start
- // ==/UserScript==
- (function () {
- 'use strict';
- let mapsUrl = '';
- let buttonAdded = false;
- const texts = {
- 'Maps': {
- 'en': 'Maps',
- 'pl': 'Mapy'
- },
- 'Open in Maps': {
- 'en': 'Open in Maps',
- 'pl': 'Otwórz w mapach'
- }
- };
- function getSearchQuery() {
- return new URLSearchParams(window.location.search).get('q');
- }
- function getUserLanguage() {
- return document.documentElement.lang || 'en';
- }
- function getText(key) {
- const userLang = getUserLanguage();
- return (texts[key] && texts[key][userLang]) || (texts[key] && texts[key].en) || key;
- }
- function updateMapsUrl() {
- const searchQuery = getSearchQuery();
- if (searchQuery) {
- mapsUrl = 'https://maps.google.com/maps?q=' + encodeURIComponent(searchQuery);
- }
- console.log('Updated mapsUrl:', mapsUrl);
- }
- function insertMapsButton() {
- console.log('Attempting to insert Maps button');
- if (!mapsUrl || buttonAdded) {
- console.log('No mapsUrl or button already added, skipping button insertion');
- return;
- }
- const existingMapsButton = document.evaluate(
- "//a[normalize-space(text())='" + getText('Maps') + "']",
- document,
- null,
- XPathResult.FIRST_ORDERED_NODE_TYPE,
- null
- ).singleNodeValue;
- if (existingMapsButton && !existingMapsButton.closest('g-popup')) {
- console.log('Updating existing Maps button');
- existingMapsButton.href = mapsUrl;
- buttonAdded = true;
- return;
- }
- const referenceAnchor = document.evaluate(
- "//div[@role='navigation']//div[@jsslot]/a | //a[contains(., 'Images')] | //a[contains(., 'Grafika')]",
- document,
- null,
- XPathResult.FIRST_ORDERED_NODE_TYPE,
- null
- ).singleNodeValue;
- if (!referenceAnchor) {
- console.log('Reference anchor not found');
- return;
- }
- console.log('Reference anchor found:', referenceAnchor);
- const mapsAnchor = referenceAnchor.cloneNode(true);
- mapsAnchor.href = mapsUrl;
- mapsAnchor.style.marginLeft = '6px';
- const spanOrDiv = mapsAnchor.querySelector('span') || mapsAnchor.querySelector('div');
- if (spanOrDiv) {
- spanOrDiv.textContent = getText('Maps');
- spanOrDiv.style.borderBottom = 'none';
- spanOrDiv.removeAttribute('selected');
- }
- referenceAnchor.parentNode.insertBefore(mapsAnchor, referenceAnchor.nextSibling);
- console.log('Maps button inserted');
- buttonAdded = true;
- }
- function setMapImageLink() {
- if (!mapsUrl) return;
- const luMapElement = document.getElementById('lu_map');
- if (luMapElement) {
- const parentAnchor = luMapElement.closest('a');
- if (parentAnchor) {
- if (!parentAnchor.href || parentAnchor.href.trim() === "") {
- parentAnchor.href = mapsUrl;
- }
- } else {
- const newAnchor = document.createElement('a');
- newAnchor.href = mapsUrl;
- luMapElement.parentNode.insertBefore(newAnchor, luMapElement);
- newAnchor.appendChild(luMapElement);
- }
- } else {
- const fallbackDiv = document.querySelector('div.V1GY4c');
- if (fallbackDiv) {
- const imgElement = fallbackDiv.querySelector('img:not([src=""])');
- if (imgElement && !imgElement.closest('a[href]:not([href=""]):not([href=" "])')) {
- const newAnchor = document.createElement('a');
- newAnchor.href = mapsUrl;
- imgElement.parentNode.insertBefore(newAnchor, imgElement);
- newAnchor.appendChild(imgElement);
- }
- }
- }
- }
- function addMapsShortcut() {
- if (!mapsUrl) return;
- const sodP3bElement = document.querySelector('.SodP3b');
- if (sodP3bElement) {
- const anchor = document.createElement('a');
- Object.assign(anchor.style, {
- position: 'absolute',
- top: '5px',
- left: '5px',
- padding: '10px',
- zIndex: '10',
- borderRadius: '20px',
- textDecoration: 'none',
- fontWeight: 'bold',
- color: getPageTextColor(), // Dynamic text color
- background: getPageBackgroundColor(), // Dynamic background color
- boxShadow: '0px 4px 6px rgba(0, 0, 0, 0.1)', // Subtle shadow
- transition: 'background 0.3s ease, color 0.3s ease' // Smooth transition
- });
- anchor.textContent = getText('Open in Maps');
- anchor.href = mapsUrl;
- // Add hover effect for better interactivity
- anchor.addEventListener('mouseenter', function () {
- anchor.style.background = invertColor(getPageBackgroundColor());
- anchor.style.color = invertColor(getPageTextColor());
- });
- anchor.addEventListener('mouseleave', function () {
- anchor.style.background = getPageBackgroundColor();
- anchor.style.color = getPageTextColor();
- });
- sodP3bElement.append(anchor);
- }
- }
- function getPageBackgroundColor() {
- const bgColor = window.getComputedStyle(document.body).backgroundColor;
- return isColorDark(bgColor) ? '#f5f5f5' : '#000'; // Light for dark background, dark for light background
- }
- function getPageTextColor() {
- const bgColor = window.getComputedStyle(document.body).backgroundColor;
- return isColorDark(bgColor) ? '#333' : '#fff'; // Light text for dark background, dark text for light background
- }
- function invertColor(hex) {
- let color = hex.substring(1); // Remove the hash
- if (color.length === 3) {
- color = color.split('').map(c => c + c).join(''); // Convert shorthand to full form
- }
- let inverted = (Number(`0x1${color}`) ^ 0xFFFFFF).toString(16).substr(1).toUpperCase();
- return `#${inverted}`;
- }
- function isColorDark(color) {
- const rgb = color.match(/\d+/g).map(Number); // Extract RGB components
- // Calculate brightness (perceived luminance formula)
- const brightness = 0.299 * rgb[0] + 0.587 * rgb[1] + 0.114 * rgb[2];
- return brightness < 128; // Dark color if brightness < 128
- }
- function setupMapsButton() {
- if (buttonAdded) {
- console.log('Button already added, skipping setup');
- return;
- }
- console.log('Setting up Maps button');
- updateMapsUrl();
- insertMapsButton();
- setMapImageLink();
- addMapsShortcut();
- }
- // Use MutationObserver to detect when the search results are loaded
- const observer = new MutationObserver((mutations, obs) => {
- const searchResults = document.getElementById('search');
- if (searchResults) {
- console.log('Search results detected, setting up Maps button');
- setupMapsButton();
- obs.disconnect(); // Stop observing once we've added the button
- }
- });
- // Start observing the document with the configured parameters
- observer.observe(document, {
- childList: true,
- subtree: true
- });
- // Also try to set up the button when the DOM is fully loaded
- document.addEventListener('DOMContentLoaded', () => {
- console.log('DOMContentLoaded event fired');
- setupMapsButton();
- });
- // Additional fallback for cases where the button might not be added
- window.addEventListener('load', () => {
- console.log('Window load event fired');
- setupMapsButton();
- });
- })();
Maps button
Posted by Anonymous on Tue 8th Oct 2024 20:14
raw | new post
view followups (newest first): Maps button by Anonymous
Submit a correction or amendment below (click here to make a fresh posting)
After submitting an amendment, you'll be able to view the differences between the old and new posts easily.
kpaste.net RSS