繁体   English   中英

如何使用GreaseMonkey在网页中插入Google地图?

[英]How to insert a Google map in a webpage using GreaseMonkey?

我尝试过的一切似乎都没有效果。 我找到了这两个链接,并认为它们会有所帮助,但这也没有用。 使用JavaScript https://developers.google.com/loader/ 动态加载JavaScript

我的Greasemonkey脚本当前大致如下:

var init_map = function() {
    new google.maps.Geocoder().geocode({address:'1125 NW 12th Ave, Portland, OR'},function(result){
        alert(result);
    });
}

function loadMaps() {
    GM_log("loadMaps called");
    google.load("maps", "3", {"callback" : init_map, "other_params":"key=foo&sensor=false"});
}

function loadScript(filename,callback){
  var fileref=document.createElement('script');
  fileref.setAttribute("type","text/javascript");
  fileref.onload = callback;
  fileref.setAttribute("src", filename);
  if (typeof fileref!="undefined"){
    document.getElementsByTagName("head")[0].appendChild(fileref);
  }
}

$(document).ready(
    function() {
        GM_log("document ready");
        loadScript('http://www.google.com/jsapi?key=ABQIAAAAfoo',function(){
            loadMaps();
        });
    }
);

我发现,如果在Greasemonkey脚本中不包含// @require http://www.google.com/jsapi?key=ABQIAAAAfoo ,则会收到google is undefined error。 如果包含它,则不会调用init_map()。 有什么建议么?

var init_map在GreaseMonkey上下文中定义一个局部变量。

如果要在网页上下文中运行JavaScript,建议在网页中注入两个<script>标记(另一种方法是在所有全局变量unsafeWindow.加上unsafeWindow.前缀):

  1. Google的地图API
  2. 您的脚本。

例:

// ==UserScript==
// @name           Name of script
// @namespace      YourNameSpaceHere
// @match          http://blabla.com/*
// @version        1.0
// @run-at         document-end
// ==/UserScript==
var head = document.head || document.documentElement;

var script = document.createElement('script');
script.src = 'http://www.google.com/jsapi?key=ABQIAAAAfoo';
head.appendChild(script);

var script2 = document.createElement('script');
script2.textContent = '... code here ..';
head.appendChild(script2);

// Clean-up:
script.parentNode.removeChild(script);
script2.parentNode.removeChild(script2);

E4X而不是纯字符串

在您的GreaseMonkey脚本中嵌入一串JavaScript代码而不转义引号和换行符的最简单选择是使用E4X格式:

script2.textContent = <x><![CDATA[ 
alert("test");
]]></x>.toString();

我将这个问题标记为与如何将Google Maps API与油腻的猴子一起使用以读取地址表并跟踪路线的重复项 但国防部“未找到任何证据支持”。

所以我将只复制粘贴我在问题中所做的操作,因为它不是重复的...
不,开个玩笑:)

让我们从您的最后一条语句开始:

我发现,如果在Greasemonkey脚本中不包含// @require http://www.google.com/jsapi?key=ABQIAAAAfoo ,则会收到google is undefined error。 如果包含它,则不会调用init_map()。 有什么建议么?

是。
首先,不应将google maps API加载为@require 而是这样做

API_js_callback = "http://maps.google.com/maps/api/js?sensor=false&region=BR&callback=initialize";

var script = document.createElement('script');
    script.src = API_js_callback;
var head = document.getElementsByTagName("head")[0];
    (head || document.body).appendChild(script);

其次,添加google = unsafeWindow.google ,否则会出现“ google is undefined”错误。
因此,您的代码应该像这样开始

var init_map = function() {
    google = unsafeWindow.google
    new google.maps.Geocoder().geocode . . . . . .

关于代码的其余部分...好吧,只需单击上面的链接,即可在其中找到如何动态创建DIV,如何向其添加地图,将DIV固定在页面上等的方法。

随意复制任何内容。

Greasemonkey脚本还是免费的:)

我在这里和其他许多地方测试了答案,但没有任何效果。 可能是因为API现在是v3或谁知道。

我将发布对我有用的答案,该答案与我发现的答案完全不同,并且我相信可以在许多其他情况下使用。 可以说这有点丑陋,但是毕竟这是脚本注入,没有人喜欢注入。

我不会在jsbin / codepen等目录中复制整个内容,因为它们根本无法复制GS(Greasemonkey)环境(至少到目前为止)和内部工作原理。

载入API

我已经控制了目标网页,所以它在那里,而不是通过GS添加。

<script  src="https://maps.googleapis.com/maps/api/js?key=my-personal-key"></script>

根据我的经验,如果您不添加密钥,则在几次请求后它将失败,您将需要等待一段时间才能再次使用。

我还有一个带有浮动窗口的div,可以在其中创建地图。

<div style="overflow:hidden; height:500px; width:700px; position:fixed; top:20px; right:20px; border:3px solid #73AD21;">
  <div id="gmap_canvas" style="height:500px;width:700px;"></div>
  <style>#gmap_canvas img{max-width:none!important;background:none!important}</style>
  <div id="Content_Title"></div>
</div>

GS脚本

// Pass whatever data you need to the window
unsafeWindow.mapdata=JSON.stringify(mapdata);



// Define content of script   
var script2 = document.createElement('script');

script2.textContent = `        
      // Get data
      mapdata=JSON.parse(window.mapdata);

      // Create map and use data
      function initializeX2() {  

          // some stuff ...        

          // Create map
          var mapCanvas = document.getElementById('gmap_canvas');
          var myLatLng = {lat: parseFloat(mapdata[max].latitude), lng: parseFloat(mapdata[max].longitude)};
          var mapOptions = {
            center: myLatLng,
            zoom: 15,
            mapTypeControl: false,
            mapTypeId: google.maps.MapTypeId.ROADMAP
          };
          var map = new google.maps.Map(mapCanvas, mapOptions);

          var marker=[];
          var contentInfoWindow=[];
          var infowindow=[];

          // Create markers
          for (var i = max ; i > max-iterations  ; i--) {  
            // Create marker
            var BLatLng={lat: parseFloat(mapdata[i].latitude), lng: parseFloat(mapdata[i].longitude)};
            console.log(BLatLng);
            marker[i] = new google.maps.Marker({
              position: BLatLng,
              map: map
            });

            // Create infowindow
            contentInfoWindow[i]=mapdata[i].number + " - " + mapdata[i].name;
            infowindow[i] = new google.maps.InfoWindow({content: contentInfoWindow[i] });

            // The function has this strange form to take values of references instead of references (pointers)
            google.maps.event.addListener(marker[i], 'click', function(innerKey) {
            return function() {
                infowindow[innerKey].open(map, marker[innerKey]);
            }
          }(i));

            // Open markers
            infowindow[i].open(map, marker[i]);

          }; // end of for

      }; // end of initializeX2           

      initializeX2();    
`;    // End of string to be added to page

// Add script to the page   
var head = document.head || document.documentElement;
head.appendChild(script2);

// Clean-up:
script2.parentNode.removeChild(script2);      

一些解释

就我而言,标记在创建时会打开,并且可能会保持打开状态。 那是我想要的行为。 如果您想要其他东西,则必须四处寻找。

这可能对您有帮助。 仅创建一个窗口,一次只能打开一个信息窗口( http://www.aspsnippets.com/Articles/Google-Maps-API-V3-Open-Show-only-one-InfoWindow-at-a-time-和-close-other-InfoWindow.aspx

如果有人获得了使用API​​ v3的其他解决方案(通过google = unsafeWindow.google ),我将非常感兴趣。

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM