簡體   English   中英

如何通過用戶腳本/同步加載谷歌地圖API?

[英]How to load the google maps api via a userscript / synchronously?

我正在編寫一個用戶腳本(greasemonkey腳本),需要將谷歌地圖添加到我無法控制的網站上的頁面。

我試圖像這樣添加腳本(在加載我嘗試的其他腳本時效果很好):

var my_script = document.createElement('script');
my_script.setAttribute('src',
             'https://maps.googleapis.com/maps/api/js?key=API_KEY&sensor=false');
document.head.appendChild(my_script);

但這失敗了:

Failed to execute 'write' on 'Document': It isn't possible to write into a 
document from an asynchronously-loaded external script unless it is explicitly
opened.

如何從用戶腳本加載和使用maps api?

根據文檔,它只能加載每個腳本的API
除非你提供參數callback
=> 異步加載Google Maps API

我沒有編寫用戶腳本的經驗,但我希望它有所幫助。

注意:不要忘記將回調函數添加到全局命名空間中。
(在普通JS中,您可以將其添加到窗口對象中。)

您必須向腳本加載添加回調函數。 如果您在phonegap中使用它,則應檢查互聯網連接,以及是否已加載。 Yuo可以問,我會給你一段代碼。

<!DOCTYPE html>
<html>
  <head>
    <title>Asynchronous Loading</title>
    <meta name="viewport" content="initial-scale=1.0, user-scalable=no">
    <meta charset="utf-8">
    <style>
      html, body, #map-canvas {
        height: 100%;
        margin: 0px;
        padding: 0px
      }
    </style>
    <script>
function initialize() {
  var mapOptions = {
    zoom: 8,
    center: new google.maps.LatLng(-34.397, 150.644)
  };

  var map = new google.maps.Map(document.getElementById('map-canvas'),
      mapOptions);
}

function loadScript() {
  var script = document.createElement('script');
  script.type = 'text/javascript';
  script.src = 'https://maps.googleapis.com/maps/api/js?v=3.exp&' +
      'callback=initialize';
  document.body.appendChild(script);
}

window.onload = loadScript;

    </script>
  </head>
  <body>
    <div id="map-canvas"></div>
  </body>
</html>

你可以嘗試在my_script添加'async'屬性,如下所示:

my_script.setAttribute('async',true);

您也可以這樣看: https//developers.google.com/maps/documentation/javascript/tutorial?hl = en#asynch

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM