简体   繁体   English

使用OpenLayers3的全局JavaScript变量

[英]Global JavaScript variable with OpenLayers3

Why is this working? 为什么这样工作?

function addMap() {
  var view = new ol.View({
    center: ol.proj.fromLonLat([29.5646, 44.1575]),
    zoom: 4
  });
  var map = new ol.Map({
    target: 'map',
    layers: [
      new ol.layer.Tile({
        source: new ol.source.OSM()
      })
    ],
    view: view
  });
}

...and this isn't? ...这不是吗?

var view = new ol.View({
  center: ol.proj.fromLonLat([29.5646, 44.1575]),
  zoom: 4
});

function addMap() {
  var map = new ol.Map({
    target: 'map',
    layers: [
      new ol.layer.Tile({
        source: new ol.source.OSM()
      })
    ],
    view: view
  });
}

I thought if variable is outside function, it's global variable and it can be used from all other places. 我想如果变量是外部函数,那是全局变量,可以在所有其他地方使用。

the issue is that you are running javascript on the document before the document has been loaded so 问题是您在文档加载之前在文档上运行javascript,因此

  1. move your javascript code to the end of the body or 将您的JavaScript代码移至正文的末尾,或
  2. you can do all this in 你可以在这一切

     $(document).ready(function() { var view = new ol.View({ center: ol.proj.fromLonLat([29.5646, 44.1575]), zoom: 4 } 

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM