My aim is to load an OpenLayers map using an external JS file. In the head I have a jQuery library, and in the body I have the OpenLayers library, my Openlayers code and the div tag.
<script type="text/javascript" src="http://example.com/OpenLayers.js"></script>
<script type="text/javascript" src="http://example.com/MyMapScript.js"></script>
<div id="map"></div>
However I don't have access to the body tag so I can't fire onload="init()"
which is how most of the examples work.
Instead, at the bottom of MyMapScript.js
I've added the line below.
jQuery(window).load(init());
This is where it gets a little odd. Using Firebug I can see that this code is called and that it initializes the map object with all it's properties. I can also see that it is calling the WMS server and getting all the map tiles successfu开发者_JAVA百科lly. However it doesn't actually draw anything on the page and no extra divs are added to the HTML.
This page talks about a similar issue but I'm not sure how to apply it to my situation as for me init()
is actually being called.
http://bytes.com/topic/javascript/answers/855670-unusual-behavior-function-calls-java-script
The solution I've gone for in the end is to do this.
<script type="text/javascript" src="http://example.com/OpenLayers.js"></script>
<script type="text/javascript" src="http://example.com/MyMapScript.js"></script>
<script type="text/javascript"> window.onload=init; </script>
<div id="map"></div>
Which works but feels like a fudge.
Is there a way to initialize an OpenLayers map from an external javascript file?
Is there anything wrong with my window.onload=init;
solution?
If I have to do it inline with the HTML is there are better way of doing it?
I fixed the issue myself. My initial code worked just fine apart from two things. I was missing the width and height on the div tag, and I had ordered the statements so that the div came after the javascript files, rather than before.
It should have looked like this.
<div id="map" style="width:400px; height:400px;"></div>
<script type="text/javascript" src="http://example.com/OpenLayers.js"></script>
<script type="text/javascript" src="http://example.com/MyMapScript.js"></script>
精彩评论