2013-08-12 3 views
1

У меня возникли проблемы с загрузкой Карты Google в iframe. Я хочу сделать something like this, но внутри iframe. Я пробовал по-разному:Как загрузить карту Google в iframe с помощью Javascript?

Пытается вызвать функцию showNewMap() перед загрузкой скрипта. Но я получаю следующее сообщение об ошибке: неперехваченный TypeError: Object [объекте глобальными] не имеет метода 'showNewMap': http://jsfiddle.net/9RE4h/1/

var iframe = document.createElement("iframe"); 
document.body.appendChild(iframe); 
var doc = iframe.contentWindow || iframe.contentDocument; 
if (doc.document) { doc = doc.document;} 

function showNewMap() { 

    var mapContainer = doc.createElement('div'); 
    mapContainer.setAttribute('style',"width: 500px; height: 300px"); 
    doc.body.appendChild(mapContainer); 

    var mapOptions = { 
     center: new google.maps.LatLng(-35.000009, -58.197645), 
     zoom: 5, 
     mapTypeId: google.maps.MapTypeId.ROADMAP 
    } 

    var map = new google.maps.Map(mapContainer,mapOptions); 
} 

var script = doc.createElement('script'); 
script.type = 'text/javascript'; 
script.src = 'https://maps.googleapis.com/maps/api/js?v=3.exp&sensor=true&' + 'callback=showNewMap'; 
doc.getElementsByTagName('head')[0].appendChild(script); 

Любую идея, чтобы решить эту проблему?

ответ

3

Firefox-Google Кр совместимы:

var iframe = document.createElement("iframe"); 
iframe.onload = function() { 
    var doc = iframe.contentDocument; 

    iframe.contentWindow.showNewMap = function() { 
    var mapContainer = doc.createElement('div'); 
    mapContainer.setAttribute('style',"width: 500px; height: 300px"); 
    doc.body.appendChild(mapContainer); 

    var mapOptions = { 
     center: new this.google.maps.LatLng(-35.000009, -58.197645), 
     zoom: 5, 
     mapTypeId: this.google.maps.MapTypeId.ROADMAP 
    } 

    var map = new this.google.maps.Map(mapContainer,mapOptions); 
} 

var script = document.createElement('script'); 
script.type = 'text/javascript'; 
script.src = 'https://maps.googleapis.com/maps/api/js?v=3.exp&sensor=true&' + 'callback=showNewMap'; 
iframe.contentDocument.getElementsByTagName('head')[0].appendChild(script); 
}; 
document.body.appendChild(iframe); 

Fiddle: http://jsfiddle.net/gS7sZ/1/

2

Проблема связана с вашей областью действия внутри JavaScript. Когда вы определили функцию showNewMap, она привязана к основному объекту окна, но вам нужно, чтобы он был определен внутри вашего iFrame. Следующие должны работать (см: http://jsfiddle.net/4Ret8/):

var iframe = document.createElement("iframe"); 
document.body.appendChild(iframe); 
var doc = iframe.contentWindow || iframe.contentDocument; 
if (doc.document) { doc = doc.document;} 

iframe.contentWindow.showNewMap = function() { 
    //debugger; 
    var mapContainer = doc.createElement('div'); 
    mapContainer.setAttribute('style',"width: 500px; height: 300px"); 
    doc.body.appendChild(mapContainer); 

    var mapOptions = { 
     center: new this.google.maps.LatLng(-35.000009, -58.197645), 
     zoom: 5, 
     mapTypeId: this.google.maps.MapTypeId.ROADMAP 
    } 

    var map = new this.google.maps.Map(mapContainer,mapOptions); 
} 

var script = doc.createElement('script'); 
script.type = 'text/javascript'; 
script.src = 'https://maps.googleapis.com/maps/api/js?v=3.exp&sensor=true&' + 'callback=showNewMap'; 
doc.getElementsByTagName('head')[0].appendChild(script); 
+0

Спасибо так много! – gal007

+0

Он не работает на Firefox :( – gal007

+1

@ gal007 Похоже, что код * может быть запущен до того, как HTML был загружен. В JSFiddle я не уверен, что будет правильным событием, чтобы убедиться, что DOM загружен сначала вы можете запустить это локально и подключиться к событию onload. – elevine

0

Функция showNewMap() не видно в кадре, необходимо добавить функцию showNewMap() в кадре

var iframe = document.createElement("iframe"); 
document.body.appendChild(iframe); 
var doc = iframe.contentWindow || iframe.contentDocument; 
if (doc.document) { doc = doc.document;} 

var func = "function showNewMap() { "+ 
    "var mapContainer = document.createElement('div');"+ 
    "mapContainer.setAttribute('style','width: 500px; height: 300px');"+ 
    "document.body.appendChild(mapContainer);"+ 

    "var mapOptions = {"+ 
    " center: new google.maps.LatLng(-35.000009, -58.197645),"+ 
    " zoom: 5,"+ 
    " mapTypeId: google.maps.MapTypeId.ROADMAP"+ 
    "};"+ 

    "var map = new google.maps.Map(mapContainer,mapOptions);"+ 
"}"; 

var scriptMap = doc.createElement('script'); 
scriptMap.type = 'text/javascript'; 
var newContent = document.createTextNode(func); 
scriptMap.appendChild(newContent); 
doc.getElementsByTagName('head')[0].appendChild(scriptMap); 

var script = doc.createElement('script'); 
script.type = 'text/javascript'; 
script.src = 'https://maps.googleapis.com/maps/api/js?v=3.exp&sensor=true&' +'callback=window.showNewMap'; 
doc.getElementsByTagName('head')[0].appendChild(script); 
+0

Это похоже на окольный путь, чтобы добраться до решения. Вам не нужно определять функцию как string. – elevine

+0

@elevine Вы знаете, как адаптировать свое решение для работы с firefox? – gal007