我在iframe中加载Google Map时遇到麻烦。我想做something like this,但是在iframe中。我以不同的方式尝试过:
尝试在加载脚本之前调用showNewMap()函数。但是我收到以下错误:未捕获的TypeError:对象[object global]没有方法'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);
有解决问题的主意吗?
最佳答案
兼容Firefox-Google Chrome:
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);
小提琴:ojita