简体   繁体   中英

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

  1. move your javascript code to the end of the body or
  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 } 

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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