无法执行'写' on' Document'使用谷歌地图(InfoWindow问题)

时间:2016-03-12 14:54:35

标签: javascript jquery google-maps google-maps-api-3

我想在我的Google地图上的infowindow中显示Tide Times

这是我的演示:http://jsfiddle.net/nvwjnrhy/1/

我的日志显示为: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 geocoder = new google.maps.Geocoder();
var marker;
var infoWindow;
var map;

function initialize() {
  var mapOptions = {
    zoom: 15,
    mapTypeId: google.maps.MapTypeId.ROADMAP
  };
  map = new google.maps.Map(document.getElementById('map-canvas'),
    mapOptions);
  setLocation();
}

function setLocation() {
  var address = '2349 Marlton Pike W, Cherry Hill, NJ 08002';
  geocoder.geocode({
    'address': address
  }, function(results, status) {
    if (status == google.maps.GeocoderStatus.OK) {
      var position = results[0].geometry.location;
      marker = new google.maps.Marker({
        map: map,
        position: position,
        title: 'Venue Name'
      });
      map.setCenter(marker.getPosition());

      
      var content = document.createElement('div');
      
      var script = document.createElement('script');
			script.src = "https://www.tidetimes.org.uk/grimsby-tide-times.js";
			content.appendChild(script);

      infoWindow = new google.maps.InfoWindow({
        content: content
      });

      google.maps.event.addListener(marker, 'click', function() {
        infoWindow.open(map, marker);
      });

      //infoWindow.open(map, marker); doesn't work
      google.maps.event.trigger(marker, 'click'); //still doesn't work
    } else {
      //
    }
  });
}

initialize();
//google.maps.event.addDomListener(window, 'load', initialize);

html, body {
  width: 100%;
  height: 100%;
}
#map-canvas {
    width: 100%;
    height: 100%;
    margin: 10px 0;
    color: #000;
}

<script src="http://maps.google.com/maps/api/js?sensor=false&.js"></script>
<div id="map-canvas"></div>
&#13;
&#13;
&#13;

感谢您对此有任何帮助:)

1 个答案:

答案 0 :(得分:1)

不是将内容直接写入文档,而是可以将内容连接起来并将其保存在变量中,例如......(使用https://www.tidetimes.org.uk/berkeley-tide-times.js

var infoBoxContent = "";
infoBoxContent += '<div style="overflow:hidden; width:'+css.width+'; height:'+css.height+'; background:'+css.background+'; border:'+css.border+'; border-radius:'+css.corner+';">';
infoBoxContent += '<h2 style="text-align:center; margin:0px; color:'+css.color+'; padding:10px 0px 0px 0px; font:bold 14px sans-serif;"><a style="color:'+css.color+'" href="https://www.tidetimes.org.uk/berkeley-tide-times" title="Berkeley Tide Times">Berkeley Tide Times</a></h2>';

依旧......

注意:您需要在本地保存脚本js文件并对其进行编辑,以便能够以这种方式使用它。

构建该字符串后,您可以直接创建InfoWindow并将内容分配给它。

var myOptions = {
     content: infoBoxContent,
     ...
};

var ib = new InfoBox(myOptions);
ib.open(theMap, marker);