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

时间:2012-02-17 13:36:43

标签: javascript google-maps greasemonkey

我尝试的任何东西似乎都没有用。 我发现这两个链接并认为它们会有所帮助,但这也没有用。 Dynamically load JavaScript with JavaScript https://developers.google.com/loader/

以下是我目前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();
        });
    }
);

我发现如果我不包括 // @require http://www.google.com/jsapi?key=ABQIAAAAfoo 在Greasemonkey脚本中,我得到一个谷歌是未定义的错误。如果我确实包含它,init_map()永远不会被调用。有什么建议吗?

3 个答案:

答案 0 :(得分:2)

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

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

  1. Google的地图API
  2. 你的剧本。
  3. 示例:

    // ==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();
    

答案 1 :(得分:1)

我将此问题标记为how to use the google maps api with greasemonkey to read a table of addresses and trace the route?的副本,但该模式“没有找到支持它的证据”。

所以我会复制粘贴我在问题中所做的事情,因为它不是重复的...
不,开玩笑吧:)。

让我们从你的上一个陈述开始:

  

我发现如果我不包括// @require   Greasemonkey中的http://www.google.com/jsapi?key=ABQIAAAAfoo   脚本,我得到一个谷歌是未定义的错误。如果我确实包括它,   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脚本无论如何都是免费的:)

答案 2 :(得分:1)

我在这里以及许多其他地方测试了答案,但没有任何方法可行。也许是因为API现在是v3或谁知道。

我将发布对我有用的答案,这与我发现的其他答案完全不同,我相信可以用于许多其他案例。它可以说有点难看,但毕竟这是脚本注入,没有人喜欢注射。

我不会在jsbin / codepen /等中复制整个东西,因为它们根本无法复制GS(Greasemonkey)环境(至少还有)和内部工作。

加载API

我控制了目的地网页,所以这不是通过GS添加的。

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

根据我的经验,如果您不添加密钥,在几次请求之后它将会失败,您将不得不等待一段时间直到它再次运行。

我还有一个浮动窗口,我会创建我的地图。

<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 SCRIPT

// 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);      

一些解释

在我的情况下,标记在创建时打开,多个标记可以保持打开状态。这是我想要的行为。如果你想要别的东西,你必须四处搜寻。

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

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