星期一, 10月 05, 2015

[GoogleMap] 如何動態載入Googlemap API

最近試著使用google map的離線api,目前google可以找到不同版本的,目前測試是3.8.2。
如果是在頁面直接透過script標籤引入mapapi.js是沒什麼大問題的!!

不過由於要實作讓使用者切換線上與離線地圖就發現了很扯的bug,
記錄以下失敗的方法,有需要的朋友可以參考。

嘗試失敗的方法

使用document.write,整個瀏覽器白畫面,無法使用且google map無法完全載入


                     var jsTag = '<' + 'script src="http://localhost:8080/js/libs/offlinemap/google/mapapi.js"' +
                        ' type="text/javascript"><' + '/script>';
                document.write(jsTag);


使用document.createElement的方法,console會噴以下這個錯誤 
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.


   var element = document.createElement("script");
                element.src = "js/libs/offlinemap/google/mapapi.js";
                element.type = "text/javascript";
                document.getElementsByTagName("head")[0].appendChild(element);

成功的方法


最後參考到這篇的解法,重新覆寫document.write方法就可以正常載入了http://stackoverflow.com/questions/3125049/cannot-add-google-map-api-script-after-pageload

 
function writeGoogleMapsScript()
            {
                document.oldWrite = document.write;
                document.write = function (text)
                {
                    console.log('new document write');
                    var parser = new DOMParser();
                    var element = parser.parseFromString(text, "text/xml");
                    var child = element.firstChild;
                    var element = document.createElement("script");
                    element.src = child.getAttribute('src');
                    element.type = "text/javascript";
                    document.getElementsByTagName("head")[0].appendChild(element);
                    document.write = document.oldWrite;
                };
                
                var element = document.createElement("script");
                element.src = "js/libs/offlinemap/google/mapapi.js";
                element.type = "text/javascript";
                document.getElementsByTagName("head")[0].appendChild(element);
            }

沒有留言:

張貼留言

留個話吧:)

其他你感興趣的文章

Related Posts with Thumbnails