我是否正确调用了JavaScript文件?

时间:2016-01-15 21:55:25

标签: javascript

我有一个网页,我想知道我的呼叫是否正确javascript3.js。该文件与html位于同一文件夹中。当我将javascript代码放在html中时,它可以正常工作。

ol3-layerswitcher.js被正确调用,所以我不知道为什么没有被调用。)

HTML:

<!DOCTYPE html>
<html>
  <head>
        <title>Map</title>
        <link rel="stylesheet" href="http://openlayers.org/en/v3.12.1/css/ol.css">
        <link rel="stylesheet" href="ol3-layerswitcher.css">
        <script src="http://openlayers.org/en/v3.12.1/build/ol.js"></script>
        <script src="ol3-layerswitcher.js"></script>
        <script src="javascript3.js"></script>
  </head>
  <body>
    <div id="map" style="width:100%;"></div>
    <div id="info"></div>
  </body>
</html>

javascript3.js:

var testSource = new ol.source.TileWMS({
url: 'http://localhost:8080/geoserver/wms',
params: {'LAYERS': 'Marine:Great_Britain', 'TILED': true},
    serverType: 'geoserver'
});

  var layers = [
    new ol.layer.Tile({
      source: new ol.source.MapQuest({layer: 'osm'})
    }),

        new ol.layer.Group({
            title: 'Layers',
            layers: [

                //Implementing layers
                new ol.layer.Tile({
                    title: 'Great Britain',
                    source: testSource
                }),
            ]
        })


  ];
  var map = new ol.Map({
    layers: layers,
    target: 'map',
    view: new ol.View({
      center: [51480.6, 7216744.2], //UK
      zoom: 5
    })
  });

  //Function to get features from layer
  map.on('singleclick', function(evt) {
    document.getElementById('info').innerHTML = '';
    viewResolution = map.getView().getResolution();
    var url = testSource.getGetFeatureInfoUrl(
        evt.coordinate, viewResolution, 'EPSG:3857',
        {'INFO_FORMAT': 'text/html'});
    if (url) {
      document.getElementById('info').innerHTML =
          '<iframe seamless src="' + url + '"></iframe>';
    }
  });


  //Layer switcher to turn layers on and off
   var layerSwitcher = new ol.control.LayerSwitcher({
   tipLabel: 'Legend'
});
map.addControl(layerSwitcher);

1 个答案:

答案 0 :(得分:0)

如果您需要执行DOM操作而不将代码包装到document ready handler(例如$(document).ready();),则正确的位置在body的末尾(或者至少在创建之后)要操纵的DOM元素:

<!DOCTYPE html>
<html>
  <head>
        <title>Map</title>
        <link rel="stylesheet" href="http://openlayers.org/en/v3.12.1/css/ol.css">
        <link rel="stylesheet" href="ol3-layerswitcher.css">
        <script src="http://openlayers.org/en/v3.12.1/build/ol.js"></script>
        <script src="ol3-layerswitcher.js"></script>
  </head>
  <body>
    <div id="map" style="width:100%;"></div>
    <div id="info"></div>
    <script src="javascript3.js"></script>
  </body>
</html>